You are on page 1of 27

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:

 A powerful collection of only 5 data types that can easily be combined.

 Strong typing, yet without declarations

 No limitations (such as max int), apart from sheer exhaustion of memory

 Refinements to support top-down programming.

 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

 string processing (regular expressions, Unicode, calculating differences between files)


 Internet protocols (HTTP, FTP, SMTP, XML-RPC, POP, IMAP, CGI programming)
 software engineering (unit testing, logging, profiling, parsing Python code)
 operating system interfaces (system calls, file systems, TCP/IP sockets).

1.1 Why is it called Python?


When he began implementing Python, Guido van Rossum was also reading the published scripts from “Monty
Python’s Flying Circus”, a BBC comedy series from the 1970s. Van Rossum thought he needed a name that was
short, unique, and slightly mysterious, so he decided to call the language Python.
1.2 Key Features of python:

 Python is an easy-to-learn and powerful object oriented programming language.


 It is a very high level programming language.
 Python is a programming language that lets you work more quickly and integrate your systems more
effectively.
 Python is free and easy to learn if you know where to start.

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

1.2.2 What is OOP ?

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

1.3. Some of Python's notable features:

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

1.4 Some programming-language features of Python are:

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

1.5 Alternative Python Implementations:

The "traditional" implementation of Python, nicknamed as CPython.

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.

A number of alternative implementations are available as well, namely

 IronPython (Python running on .NET)

 Jython (Python running on the Java Virtual Machine)

 PyPy (A fast python implementation with a JIT compiler)

 Stackless Python (Branch of CPython supporting microthreads)

 MicroPython (Python running on micro controllers)

Other parties have re-packaged CPython. These re-packagings often include more libraries or are specialized for
a particular application:

 pythonxy (Scientific-oriented Python Distribution based on Qt and Spyder)

 winpython (WinPython is a portable scientific Python distribution for Windows)

 Conceptive Python SDK (targets business, desktop and database applications)

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

Latest Python: Release/version 3 –python 3.8.3 on May 13, 2020.

Release/version2-python 2.7.18 on April 20,2020

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:

NumPy : Base N- dimensional array package.

SciPy library- Fundamental library for Scientific Computing.

4
IPython – Interactive Python for Interactive Computing and provides a rich architecture for interactive
computing.

SymPy – Symbolic Mathematics

Pandas – Data structures & Analysis.

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.

Latest version: 1.0.3, Released on Mar 18, 2020.

1.6 Applications for Python:


 Web and Internet Development
 Scientific and Numeric
 Education
 Desktop GUIs
 Software Development
 Business Applications

Web and Internet Development

Python offers many choices for web development (Client & Server Programming):

 Frameworks such as Django and Pyramid.


 Micro-frameworks such as Flask and Bottle.
 Advanced content management systems such as Plone and django CMS.

Python's standard library supports many Internet protocols:

 HTML and XML


 JSON
 E-mail processing.
 Support for FTP, IMAP, and other Internet protocols.
 Easy-to-use socket interface.

Scientific and Numeric

Python is widely used in scientific and numeric computing:

 SciPy is a collection of packages for mathematics, science, and engineering.


 Pandas is a data analysis and modeling library.
 IPython is a powerful interactive shell that features easy editing and recording of a work session, and
supports visualizations and parallel computing.

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.

SCons for build control.


Buildbot and Apache Gump for automated continuous compilation and testing.
Roundup or Trac for bug tracking and project management.

Business Applications:

Python is also used to build ERP and E-commerce systems:

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.

Tryton is a three-tier high-level general purpose application platform.

1.2 Python pluses


1)Easy to use

2)Expressive language

3)Interpreted language

4)Its completeness

6
5)Cross-platform language

6)Free and Open source

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

1.3 Minuses of Python (Drawbacks)


a) Not the fastest language
b) Lesser libraries than C, Java, Perl.
c) Not Strong on Type –binding
b) Not easily Convertible

1.4 Interpretation V/s Compilation


Programming Languages:
To write a computer program, a standard programming language is used.

A programming language is composed of a set of instructions in a language understandable to the


programmer and recognizable by a computer.
Programming languages can be classified as high-level and low level.

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.

How python interpreter works?

9
Note: Any language can be implemented with a compiler or with an interpreter.

• A combination of both solutions is also common:


A compiler can translate the source code into some intermediate form (often called p-
code or bytecode), which is then passed to an interpreter which executes it.
Linker:
• In computing, a linker or link editor is a computer System program that takes one or
more object files generated by a compiler or an assembler and combines them into a
single executable file, library file, or another 'object' file.
• A simpler version that writes its output directly to memory is called the loader,
though loading is typically considered a separate process.

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.

1.5 Solved Problems:


1)Who developed Python programming language?

Guido Van Rossum in 1990s

2) Is python an object oriented language?

Yes

3)’Python is an Interpreted high level language’. What does it mean to you?

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.

4) Python programming language got its name from which show?

Python programming language was named after a British TV show namely ‘Monty Python’s Flying
circus.’

5)What does a cross platform language mean?

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.

7) What is the differences between Interactive and Scripting mode in Python?

We can use Python Interpreter in two modes:

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.

9) valid string formats in Python - “Hello” , ‘Hello’.

Glossary:
Cross-Platform - Something that is compatible across various platforms.

Open source – Computer software for which source-code is freely available.

Python shell –is an interactive interpreter of Python.

Source code –Complete program instructions.

1.6. Python used as a Calculator


>>> 2+2 # addition of Two numbers

>>> 50-5*6 # arithmetic operation

20

>>> (50-5*6)/4 # arithmetic operation

5.0

>>> 8/5 #Division

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.

Note: The ** operator to calculate powers in python

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

SyntaxError: Missing parentheses in call to 'print'. Did you mean print(area)?

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

File "<pyshell#27>", line 1, in <module>

height

NameError: name 'height' is not defined

The _ (underscore operator):

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

Finding square root of a given number


x power ½ = square root of x
number=int(input("Enter a number"))
sqrt=number**0.5
print("square root",sqrt)

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)

#Method 2 for runtime execution


import math
sroot=int(input("Enter a number"))
root=math.sqrt(sroot)
print(root)

1.7 Working with Python:


To start & work on Python,

Start All programsPython 3.8  1) Python 3.8 (32 bit)— For CLI

(Command Line Interface)

OR

2) IDLE (Python 3.8 , 32-bit) --- For GUI

(Graphical User Interface)

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.

Working Modes of Interpreter:

We can use Python Interpreter in two modes:

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.

What we are seeing is called Python Shell.


>>> is known as the prompt string, it simply means that Python shell is ready to accept user
commands.
Python shell allows you to type Python code and see the result immediately.
In technical jargon(Terminology), this is also known as REPL short for Read-Eval-Print-Loop.
Just like a Calculator.
In Python shell, enter the following calculations one by one and hit ENTER key to get the
result.

16
 Commands such as 17 / 3, print("Hello Python") are known as statements in
programming.

 A statement is simply an instruction for the Python interpreter to execute.

A program usually consists of sequence of statements.

How to Quit From Python?

To quit the Python shell in Windows hit Ctrl+Z followed by the Enter Key,

(Or ) We can call quit().

(or) FileExit (or Ctrl+Q)

To terminate or close a file , File  close.

On Linux or Mac hit Ctrl+D followed by the Enter key.

In Python, we use print() function to print something to the screen.


In the Python shell type print("Hello Python") and hit enter:

17
We have just used two important programming constructs – A function and a string.

1. print() is a function – A function in programming is a chunk of code which does something


very specific. In our case, the print() function prints the argument (i.e "Welcome to
Python shell”) it is given to the console.
2. A string is just a sequence of characters enclosed inside single or double quotes.

For example: "hai", 'hello' are strings,

“hello’, ’hello” ,[hello] - are not strings.

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:

>>> _ #To get last saved/stored data item.

----------------------------------------------------------------------------------------------------------------

Example 3: #adding two values by use of variables.

>>> a=12

>>> b=3

>>> a+b

15

----------------------------------------------------------------------------------------------------------------

Example 4:

>>> 5*3 # multiplication of two numbers

15

---------------------------------------------------------------------------------------------------------------

Example 5:

>>> print "python"

File "<stdin>", line 1

print "python"

SyntaxError: Missing parentheses in call to 'print'. Did you mean print("python")?

>>> print("python")

python

------------------------------------------------------------------------------------------------------------------------

Example 6:

>>> sqrt(4)

19
Traceback (most recent call last):

File "<stdin>", line 1, in <module>

NameError: name 'sqrt' is not defined

>>> import math

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

File "<stdin>", line 1

print c

SyntaxError: Missing parentheses in call to 'print'. Did you mean print(c)?

>>> print(c)

30

--------------------------------------------------------------------------------

>>> abs(2)

20
2

>>> abs(2.566)

2.566

---------------------------------------------------------------------

>>> sqrt(9)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

NameError: name 'sqrt' is not defined

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

hai hello how are you

>>> s

21
' hello how are you'

>>> name=input('keerthi')

keerthi

>>> name

''

>>> name=input('keerthi')

keerthi enter your name

>>> name

' enter your name'

-----------------------------------------------------------------------------------------------------------------------

>>> len('keerthi')

>>> len(keerthi)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: object of type 'int' has no len()

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

By convention, all Python programs have .py extension.


The file eo.py is called source code or source file or script file or module.

To execute the program,


RunRun Module.

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.

1.8 Types of Errors

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.

Here are some of the common causes of Syntax 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.

The following Python shell sessions demonstrate some Syntax errors:

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

Here are some other common causes of runtime errors:

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

IDLE has the following features:

 coded in 100% pure Python, using the tkinter GUI toolkit


 cross-platform: works mostly the same on Windows, Unix, and macOS
 Python shell window (interactive interpreter) with colorizing of code input, output, and
error messages
 multi-window text editor with multiple undo, Python colorizing, smart indent, call tips,
auto completion, and other features
 search within any window, replace within editor windows, and search through multiple
files (grep)
 debugger with persistent breakpoints, stepping, and viewing of global and local
namespaces
 configuration, browsers, and other dialogs
Menus
IDLE has two main window types, the Shell window and the Editor window. It is possible to
have multiple editor windows simultaneously. On Windows and Linux, each has its own top
menu. Each menu documented below indicates which window type it is associated with.

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

You might also like