Professional Documents
Culture Documents
Unit 1 Python Chapter 1
Unit 1 Python Chapter 1
INTRODUCTION TO PYTHON
1. Introduction
Developed by Guido Van Rossum in February 1991.
Python is based on TWO languages, Such as ABC language and Modula -3.
ABC language:
ABC is an interactive programming language and environment for personal computing, originally intended as
a good replacement for BASIC language. It was designed by first doing a task analysis of the programming task.
BASIC: Beginners' All-purpose Symbolic Instruction Code or Beginners All-purpose Symbolic Instruction Code)
is a family of general-purpose, high-level programming languages.
ABC is easy to learn and yet easy to use. Originally intended as a language for beginners, it has evolved into a
powerful tool for beginners and experts alike.
1
Some features of ABC language:
Nesting by indentation
Programs typically one fourth or one fifth the size of the equivalent Pascal or C language.
Top down programming: The "top down" approach takes a high level definition of the problem and subdivides
it into sub-problems, further divided into small problems that can easily documented and coded. Also called as
"stepwise refinement," it is a software development technique that imposes a hierarchical structure on the design
of the program.
Modula-3 is a modern programming language that supports interfaces, objects, lightweight threads of control,
the isolation of unsafe code, garbage collection, exceptions, and subtyping.
Interest in Modula-3 is growing, both in industry and academia. Like Linux, Modula-3 is a powerful piece of
software built and maintained by enthusiastic programmers.
Python is a high-level general-purpose programming language that can be applied to many different
classes of problems.
This language comes with a large standard library that covers areas such as
Python is a clear and powerful object-oriented programming language, comparable to Perl, Ruby,
Scheme, or Java.
2
1.2.1 What is OSI ?
The Open Source Initiative (OSI) is a non-profit corporation with global scope formed to educate about and
advocate for the benefits of open source and to build bridges among different constituencies in the open source
community.
Open source enables a development method for software that harnesses the power of distributed peer review and
transparency of process. The promise of open source is higher quality, better reliability, greater flexibility, lower
cost, and an end to predatory vendor lock-in.
Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can
contain data, in the form of fields (often known as attributes or properties), and code, in the form of procedures
(often known as methods).
Uses an elegant syntax, making the programs you write easier to read.
It is an easy-to-use language that makes it simple to get your program working. This makes Python ideal
for prototype development and other ad-hoc programming tasks, without compromising maintainability.
Comes with a large standard library that supports many common programming tasks such as connecting
to web servers, searching text with regular expressions, reading and modifying files.
Python's interactive mode makes it easy to test short snippets of code. There's also a bundled development
environment called IDLE.
Is easily extended by adding new modules implemented in a compiled language such as C or C++.
Can also be embedded into an application to provide a programmable interface.
Runs anywhere, including Mac OS, Windows, Linux, and Unix, with unofficial builds also available
for Android and iOS.
Is free software in two senses. It doesn't cost anything to download or use Python, or to include it in your
application. Python can also be freely modified and re-distributed because while the language is
copyrighted it's available under an open-source license.
A variety of basic data types are available: numbers (floating point, complex, and unlimited-length long
integers), strings (both ASCII and Unicode), lists, and dictionaries.
Python supports object-oriented programming with classes and multiple inheritances.
Code can be grouped into modules and packages.
The language supports raising and catching exceptions, resulting in cleaner error handling.
Data types are strongly and dynamically typed. Mixing incompatible types (e.g. attempting to add a
string and a number) causes an exception to be raised, so errors are caught sooner.
Python contains advanced programming features such as generators and list comprehensions.
Python's automatic memory management frees you from having to manually allocate and free memory
in your code.
3
CPython is the default and most widely used implementation of the language. CPython can be defined as both
an interpreter and a compiler as it compiles Python code into bytecode before interpreting it.
Other parties have re-packaged CPython. These re-packagings often include more libraries or are specialized for
a particular application:
Anaconda Python (a full Python distribution for data management, analysis and visualization of large
data sets)
If you want to host and run Python in the cloud, these implementations may be right for you:
PythonAnywhere (freemium hosted Python installation which lets you run Python in the browser, e.g.
for tutorials, showcases, etc.)
Anaconda was built by data scientists, for data scientists. More than 20 million people use our technology to
solve the toughest problems.
Anaconda solutions are serious technology for real data science and ML (Machine Learning) applications.
Anaconda is a free collection of powerful packages for Python that enables large-scale data management,
analysis, and visualization for Business Intelligence, Scientific Analysis, Engineering, Machine Learning, and
more.
SciPy (pronounced “Sigh Pie”) is a Python-based ecosystem of open-source software for mathematics,
science, and engineering. In particular, these are some of the core packages:
4
IPython – Interactive Python for Interactive Computing and provides a rich architecture for interactive
computing.
pandas is a fast, powerful, flexible and easy to use open source data analysis and manipulation tool, built on
top of the Python programming language.
Python offers many choices for web development (Client & Server Programming):
Education
5
Python is a superb language for teaching programming, both at the introductory level and in more
advanced courses.
Desktop GUIs
The Tk (Tool Kit) GUI library is included with most binary distributions of Python.
Some toolkits that are usable on several platforms are available separately:
wxWidgets
Kivy, for writing multitouch applications.
Qt via pyqt or pyside
Software Development
Python is often used as a support language for software developers, for build control and management,
testing, and in many other ways.
Business Applications:
Enterprise Resource Planning (ERP) – it is a business process management software that manages and
integrates a company's financials, supply chain, operations, reporting, manufacturing, and human resource
activities.
Odoo is an all-in-one management software that offers a range of business applications that form a complete
suite of enterprise management applications.
2)Expressive language
3)Interpreted language
4)Its completeness
6
5)Cross-platform language
7)Variety of Usage/Applications
a) Scripting
b) Web Applications
c)Game Development
d)System administrations
e) Rapid Prototyping
f) GUI programs
g) Database Applications
Rapid prototyping is the speedy creation of a full-scale model. The word prototype comes from the Latin
words proto (original) and typus (model).In software development, when a small team quickly builds a working
software program for users to review, it is also called rapid prototyping. It may also be called rapid application
development (RAD).
Low-level programming languages were the first category of programming languages to evolve.
Gradually, high-level languages were developed and put to use.
a) Low-level Languages: A low-level computer programming language is one that is closer to the native
language of the computer, which is 1‟s and 0‟s.
7
b) Machine Language: Only computer can directly understand only its own machine language.
Machine language is the natural language of a particular computer. It is defined by the hardware design
of that computer. This is considered to be the First Generation Language (1GL).
Advantages: The CPU directly understands machine instructions and hence no translation is required.
Therefore, the computer directly starts execute the machine language instructions, and it takes less
execution time.
c) High-Level Languages: Since a computer prefers machine language while a person wants to use a natural
language special “high level computer languages have been developed to bridge this communication gap.
A high level language like C, uses English words plus symbols and numbers. Very first two high level
languages are FORTRAN and COBOL. This is considered to be a Third Generation Language (3GL).
Advantages:
Readability Programs written in these languages are more readable than those written in assembly and machine
languages.
Portability High-level programming languages can be run on different machines with little or no change.
Easy debugging error can be easily detected and removed.
Ease in the development of Software Since commands of these programming languages are closer to the
English language, software can be developed with ease.
What is a Translator?
• Software program , that converts code from one computer language into another.
• Also known as Programming language processor.
• Translations between high level low level, High level Intermediate level.
• Similar levels also { high high , low low @ different computing platforms}.
Examples :
High-level : C, C++ ,Java, Python etc.
Intermediate-level languages : Java bytecode
low-level languages : assembly language and machine level language.
Types of Translator:
• Compiler
• Interpreter
• Assembler
Compiler : Used to convert high-level programming language to low-level programming
language.
• It converts the whole program in one session and reports errors detected after the conversion.
8
• It is processor-dependent & platform-dependent program.
•The compiler takes source files with extensions like .c (for C ) , .py (Python) and produces
corresponding .o (Object) files.
Interpreter:
• Similar to a compiler
• Used to convert high-level programming language to low-level programming language.
• The difference is that it converts the program one line of code at a time and reports errors
when detected, while also doing the conversion.
• An interpreter is faster than a compiler as it immediately executes the code upon reading the
code.
• It is often used as a debugging tool for software development as it can execute a single line
of code at a time.
9
Note: Any language can be implemented with a compiler or with an interpreter.
Compilation is the process the computer takes to convert a high-level programming language into a
machine language that the computer can understand. The software which performs this conversion is
called a compiler.
Interpretation is the process the computer takes to convert a high-level programming language into
a machine language that the computer can understand and gets output immediately. The software
which performs this conversion is called an Interpreter.
10
Interpretation is reading or checking the code line by line and if any error is found you can't go further before
correcting it. whereas compilation is reading and checking the whole code at once and reporting all errors found
in it.
Yes
Python is a High level language, means it is programmer-friendly i.e easy to program and comprehend.
Python is an Interpreted language, means it requires an interpreter (Not compiler) to execute its code
line by line- one statement at a time.
Python programming language was named after a British TV show namely ‘Monty Python’s Flying
circus.’
It means that “ it can run well on variety of platforms like Windows, Linux/Unix , Macintosh etc.
6)Python is a Free and open source language. What do you understand by this feature?
11
It means that “ To download Python , one needs not to pay anything, because it is FREE. And its source
code is also available, which can be modified /improved etc, because it is Open source.
1. Interactive Mode.
2. Script Mode.
In Interactive Mode, Python interpreter waits for user to enter the command. When we type the
command, Python interpreter goes ahead and executes the command, then it waits again for next command.
In Script mode, Python Interpreter runs a program from the source file.
Glossary:
Cross-Platform - Something that is compatible across various platforms.
20
5.0
1.6
12
>>> 17/3 #Division always returns a floating point number
5.666666666666667
Floor Division:
Mathematical division that rounds down to nearest integer. The floor division operator is //. It always
returns an integer value.
>>> 17//3 # Floor division discards the fractional part
>>> 17%3 # Modulo division always returns remainder value of the division.
>>> 5**2
25
>>> 2**7
128
The = (equal to) operator:
The equal sign (=) is used to assign a value to a variable. Afterwards, no result is displayed before
the next interactive prompt:
>>> length=10
>>> width=40
>>> area=length*width
>>> print(area)
400
Note: Syntax Error: If we do not follow the rules, it will generate syntax error
>>> print(area)
400
Name error:
If a variable is not “defined” (assigned a value), trying to use it will give you an error:
>>> height
13
Traceback (most recent call last):
height
In interactive mode, the last printed expression or vale is assigned to the variable _. This means that
when you are using Python as a desk calculator, it is somewhat easier to continue calculations, for
example:
>>> (pa,time,ri)=(50000,1,8)
>>> si=(pa*time*ri)/100
>>> tot=pa+_
>>> print(tot)
54000.0
Output:
>>>
Enter a number4
square root 2.0
>>>
Enter a number16
square root 4.0
>>>
Enter a number15
square root 3.872983346207417
14
Given number statically
import math
sroot=math.sqrt(16)
print(sroot)
Start All programsPython 3.8 1) Python 3.8 (32 bit)— For CLI
OR
1) Python Shell is a Command line tool that starts up the python interpreter.
We can test simple programs and also write some short programs.
However, in order to write a more complexed python program, we need an editor.
2) IDLE (Integrated Development & Learning Environment), has combined the above two needs
and bundled them as a package.
IDLE consists of Python Shell, and Text editor used to create, develop and implement user
programs for easy of use.
IDLE= Shell+ Editor
15
we have installed Python Interpreter to execute commands.
An Interpreter is a program, which translates our code in high level language into machine
language and then executes it line by line.
1.Interactive Mode.
2. Script Mode.
In Interactive Mode, Python interpreter waits for user to enter the command. When we type the
command, Python interpreter goes ahead and executes the command, then it waits again for
next command.
In Script mode, Python Interpreter runs a program from the source file.
Interactive Mode:
Python interpreter in interactive mode is commonly known as Python Shell.
16
Commands such as 17 / 3, print("Hello Python") are known as statements in
programming.
To quit the Python shell in Windows hit Ctrl+Z followed by the Enter Key,
17
We have just used two important programming constructs – A function and a string.
Note:
We know that in the Python Shell, if we type any expression/Statement and hit enter, the Python
interpreter evaluates the expression and displays the result.
Example 1:
18
>>> 2+3 # adding two numerical numbers
--------------------------------------------------------------------------------------------------------------
Example 2:
----------------------------------------------------------------------------------------------------------------
>>> a=12
>>> b=3
>>> a+b
15
----------------------------------------------------------------------------------------------------------------
Example 4:
15
---------------------------------------------------------------------------------------------------------------
Example 5:
print "python"
>>> print("python")
python
------------------------------------------------------------------------------------------------------------------------
Example 6:
>>> sqrt(4)
19
Traceback (most recent call last):
>>> math.sqrt(4)
2.0
------------------------------------------------------------------------------------------------------------
Example 7:
>>> a=2
>>> b=3
>>> c=a+b
>>> print(c)
-----------------------------------------------------------------------------------------------------------
>>> a=10
>>> b=20
>>> a+b
30
>>> c=a+b
>>> print c
print c
>>> print(c)
30
--------------------------------------------------------------------------------
>>> abs(2)
20
2
>>> abs(2.566)
2.566
---------------------------------------------------------------------
>>> sqrt(9)
>>> math.sqrt(9)
3.0
-------------------------------------------------------------------------------------------------------------------
>>> bin(4)
'0b100'
>>> bin(3)
'0b11'
-----------------------------------------------------------------------------------------------------------
>>> x=10
>>> eval('x+10')
20
-----------------------------------------------------------------------------------------------------------------
>>> x=10
>>> id(x)
263452736
>>> keerthi=100
>>> id(keerthi)
263454176
>>> s=input('hai')
>>> s
21
' hello how are you'
>>> name=input('keerthi')
keerthi
>>> name
''
>>> name=input('keerthi')
>>> name
-----------------------------------------------------------------------------------------------------------------------
>>> len('keerthi')
>>> len(keerthi)
>>> len('mani')
>>> len('123456978')
------------------------------------------------------------------------------------------------------------------
>>> max(10,5)
10
>>> min(10,5)
>>> pow(2,10)
1024
>>> pow(2,2)
22
4
>>>
Script Mode:
Python Shell is good for testing small chunks of code but there is one problem – the statements
you enter in the Python shell are not saved anywhere.
In case, we want to execute the same set of statements multiple times, it would be better off to
save the entire code in a file. Then, use the Python interpreter in script mode to execute the
code from a file.
Create a new directory named python101, you can create this directory anywhere you want, just
remember the location because we will use this directory to store all our programs. Create
another directory inside python101 named Chapter-01 to store the source files for this chapter.
To create programs, you can use any text editor, just make sure to save your file as plain text.
Create a new file named eo.py inside Chapter-01 directory add the following code to it:
python101/Chapter-01/eo.py
23
Note: On Windows use python eo.py to execute the program.
This command starts the Python interpreter in script mode and executes the statements in
the eo.py file.
In programming errors are inescapable, sooner or later you will encounter one. Programming errors
are mainly divided into three types:
1. Syntax Errors.
2. Runtime Errors.
3. Logical Errors.
Syntax Errors
24
The syntax is a set of rules to properly write a Computer language. Syntax errors happen when we do
not follow the syntax rules. They commonly occur in our code due to a typo.
When a syntax error is encountered in the program, the execution of the program is halted and Python
interpreter displays an error message explaining the probable cause of the error.
The syntax error occurs when the statement is being translated to machine language but before it is
executed. A component of interpreter called parser discovers these errors.
1. Misspelled keywords.
2. Incorrect use of an operator.
3. Omitting parentheses in a function call.
4. Not wrapping strings in single quotes or double quotes.
and so on.
Example 1:
1 >>>
2 >>> 4 +
3 File "<stdin>", line 1
4 4+
5 ^
6 SyntaxError: invalid syntax
7 >>>
In the above example, we are attempting to add two numbers, but we forgot to include the second number.
That’s why Python interpreter reports SyntaxError. Also, notice that the caret symbol (^) points to a position
where Python interpreter thinks is the cause of the problem.
Example 2:
1 >>>
2 >>> print("Big Python)
3 File "<stdin>", line 1
4 print("Big Python)
5 ^
6 SyntaxError: EOL while scanning string literal
In this case, we forgot to end the string with double quotes, that’s why syntax error in encountered. Notice again
that the caret symbol is pointing to the position where Python interpreter thinks is the cause of the problem.
Fixing syntax errors is quite easy, you just have to train our eyes to look for the caret symbol (^).
25
Runtime Errors
As the name says, Runtime Errors are errors which occurs while the program is running. Just like Syntax
errors, when they are encountered execution of the program is halted and interpreter displays a message about
the probable cause of the problem.
They usually occur when interpreter counters an operation that is impossible to carry out.
One such operation is dividing a number by 0. Since dividing a number by 0 is undefined.
When interpreter encounters dividing by 0 operation it raises ZeroDivisionError as follows:
1 >>>
2 >>> 99/0
3 Traceback (most recent call last):
4 File "<stdin>", line 1, in <module>
5 ZeroDivisionError: division by zero
6 >>>
1. Runtime error may occur when we try to create a new variable and the system runs out of memory.
2. Trying to use a function or variable which is not yet defined.
3. Accessing a file which doesn’t exist.
and so on.
Logical Errors
Logical error occurs when the program produces incorrect results. For example, let’s say we are creating a
simple program to convert temperature from Fahrenheit to Celsius as follows:
python101/Chapter-03/fah_to_cel.py
1 print("20 degree Fahrenheit in degree Celsius is: ")
2 print(5 / 9 * 20 - 32)
Output:
1 20 degree Fahrenheit in degree Celsius is:
2 -20.88888888888889
The above program outputs -20.88888888888889, which is wrong. The correct value is -6.666. These types of
errors are called logical errors. To get the correct answer use 5 / 9 * (20 - 32) instead of 5 / 9 * 20 - 32. The
parentheses around 20 - 32, forces Python to perform subtraction before division and multiplication.
We can use also use the print() function to print the value of a variable like this:
1 >>>
2 >>> age = 100
3 >>> print(age)
4 100
26
5 >>>
1.9 More about IDLE is Python’s Integrated Development and Learning Environment
Output windows, such as used for Edit => Find in Files, are a subtype of editor window. They
currently have the same top menu but a different default title and context menu.
On macOS, there is one application menu. It dynamically changes according to the window
currently selected. It has an IDLE menu, and some entries described below are moved around
to conform to Apple guidelines.
27