Bcaty Unit-1 Python Notes Modified
Bcaty Unit-1 Python Notes Modified
Introduction:
Python is a widely used high-level, interpreted programming language. It was created by Guido van Rossum
in 1991 and further developed by the Python Software Foundation. It was designed with an emphasis on
code readability, and its syntax allows programmers to express their concepts in fewer lines of
code. Python is a programming language that lets you work quickly and integrate systems more efficiently.
Features of python:
1) It’s Object-Oriented and Functional: Python is an object-oriented language, from the ground up. Its
class model supports advanced notions such as polymorphism, operator overloading, and multiple
inheritance;
2) It’s Free: Python is completely free to use and distribute. As with other open source software, such as
Tcl, Perl, Linux, and Apache, you can fetch the entire Python system’s source code for free on the
Internet.
3) It’s Portable: It’s Powerful: From a features perspective, Python is something of a hybrid. Its toolset
places it between traditional scripting languages (such as Tcl, Scheme, and Perl) and systems
development languages (such as C, C++, and Java). The standard implementation of Python is written
in portable ANSI C, and it compiles and runs on virtually every major platform currently in use.
4) Dynamic typing: Python keeps track of the kinds of objects your program uses when it runs; it doesn’t
require complicated type and size declarations in your code. In fact, there is no such thing as a type or
variable declaration anywhere in Python. Because Python code does not constrain data types, it is also
usually automatically applicable to a whole range of objects.
5) Automatic memory management: Python automatically allocates objects and reclaims (“garbage
collects”) them when they are no longer used, and most can grow and shrink on demand.
6) Programming-in-the-large support: For building larger systems, Python includes tools such as
modules, classes, and exceptions. These tools allow you to organize systems into components, use OOP
to reuse and customize code, and handle events and errors gracefully.
7) Built-in object types: Python provides commonly used data structures such as lists, dictionaries, and
strings as intrinsic parts of the language; as you’ll see, they’re both flexible and easy to use.
8) Built-in tools: To process all those object types, Python comes with powerful and standard operations,
including concatenation (joining collections), slicing (extracting sections), sorting, mapping, and more.
9) Library utilities: For more specific tasks, Python also comes with a large collection of precoded
library tools that support everything from regular expression matching to networking. Once you learn
the language itself, Python’s library tools are where much of the application-level action occurs.
10) It’s Mixable Python programs can easily be “glued” to components written in other languages in a
variety of ways.
What Can I Do with Python?
As a general-purpose language, Python’s roles are virtually unlimited: you can use it for everything
from website development and gaming to robotics and spacecraft control. However, the most common
Python roles currently seem to fall into a few broad categories-
Systems Programming: Python’s built-in interfaces to operating-system services make it ideal for
writing portable, maintainable system-administration tools and utilities (sometimes called shell tools).
Python programs can search files and directory trees, launch other programs, do parallel processing
with processes and threads, and so on.
GUIs: Python’s simplicity and rapid turnaround also make it a good match for graphical user interface
programming on the desktop.
Internet Scripting: Python comes with standard Internet modules that allow Python programs to
perform a wide variety of networking tasks, in client and server modes. Scripts can communicate over
sockets; extract form information sent to server-side CGI scripts; transfer files by FTP; parse and
generate XML and JSON documents; send, receive, compose, and parse email; fetch web pages by
URLs; parse the HTML of fetched web pages; communicate over XMLRPC, SOAP, and Telnet; and
more. Python’s libraries make these tasks remarkably simple.
Component Integration: Python’s ability to be extended by and embedded in C and C++ systems
makes it useful as a flexible glue language for scripting the behavior of other systems and components.
For instance, integrating a C library into Python enables Python to test and launch the library’s
components, and embedding Python in a product enables onsite customizations to be coded without
having to recompile the entire product
Database Programming: For traditional database demands, there are Python interfaces to all
commonly used relational database systems—Sybase, Oracle, Informix, ODBC, MySQL, PostgreSQL,
SQLite, and more. The Python world has also defined a portable database API for accessing SQL
database systems from Python scripts, which looks the same on a variety of underlying database
systems.
Rapid Prototyping: To Python programs, components written in Python and C look the same. Because
of this, it’s possible to prototype systems in Python initially, and then move selected components to a
compiled language such as C or C++ for delivery. Unlike some prototyping tools, Python doesn’t
require a complete rewrite once the prototype has solidified. Parts of the system that don’t require the
efficiency of a language such as C++ can remain coded in Python for ease of maintenance and use.
Numeric and Scientific Programming: Python is also heavily used in numeric programming—a
domain that would not traditionally have been considered to be in the scope of scripting languages, but
has grown to become one of Python’s most compelling use cases. Prominent here, the NumPy high-
performance numeric programming extension for Python. The popular SciPy and Scientific Python
extensions, for example, provide additional libraries of scientific programming tools and use NumPy as
a core component.
The Python Interpreter:
The Python interpreter is a program that can read Python programming statements and execute them.
(Sometimes we will refer to the Python interpreter simply as the interpreter.) You can use the
interpreter in two modes: interactive mode and script mode.
In interactive mode, the interpreter waits for you to type Python statements on the keyboard. Once you
type a statement, the interpreter executes it and then waits for you to type another statement.
In script mode, the interpreter reads the contents of a file that contains Python statements. Such a file
is known as a Python program or a Python script. The interpreter executes each statement in the Python
program as it reads it. Once Python has been installed and set up on your system, you start the
interpreter in interactive mode by going to the operating system's command line and typing the
following command: python
If you are using Windows, you can alternatively click the Start button, then All Programs. You should
see a program group named something like Python 2.5. (The "2.5" is the version of Python that is
installed. At the time this is being written, Python 2.5 is the latest version.) Inside this program group
you should see an item named Python (command line). Clicking this menu item will start the Python
interpreter in interactive mode. When the Python interpreter starts in interactive mode, you will see
something like the following displayed in a console window: Python 2.5.1 (r251:54863, Apr 18 2007,
08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for
more information. >>>
The >>> that you see is a prompt that indicates the interpreter is wait& for you to type a Python
statement.
Writing Python Programs and Running Them in Script Mode:
Although interactive mode is useful for testing code, the statements that you enter in interactive mode
are not saved as a program. They are simply executed and their results displayed on the screen. If you
want to save a set of Python statements as a program, you save those statements in a file. Then, to
execute the program, you use the Python interpreter in script mode. For example, suppose you want to
write a Python program that displays the following three lines of text:
Nudge nudge
Wink wink
Know what I mean?
To write the program you would use a simple text editor like Notepad (which is installed on
all Windows computers) to create a file containing the following statements:
print 'Nudge nudge '
print 'Wink wink'
print ' Know what I mean? '
When you save a Python program, you give it a name that ends with the . py extension,
which identifies it as a Python program. For example, you might save the program
previously shown with the name test .py . To run the program, you would go to the
directory in which the file is saved and type the following command at the operating system
command line:
python test.py This starts the Python interpreter in script mode and causes it to execute the
statements in
the file test.py. When the program finishes executing, the Python interpreter exits
Operators: -
Operators are the basis for both control and management of data within applications. You use
operators to define how one piece of data is compared to another and to modify the information within a
single variable. In fact, operators are essential to performing any sort of math-related task and to assigning
data to variables in the first place. When using an operator, you must supply either a variable or an
expression. You already know that a variable is a kind of storage box used to hold data.
An expression is an equation or formula that provides a description of a mathematical concept. In
most cases, the result of evaluating an expression is a Boolean (true or an operator accepts one or more
inputs in the form of variables or expressions, performs a task (such as comparison or addition), and then
provides an output consistent with that task. Operators are classified partially by their effect and partially
by the number of elements they require. For example, a unary operator works with a single variable or
expression; a binary operator requires two.
The elements provided as input to an operator are called operands. The operand on the left side
of the operator is called the left operand, while the operand on the right side of the operator is called the
right operand. The following list shows the categories of operators that you use within Python:
✓ Unary
✓ Arithmetic
✓ Relational
Logical
✓ Bitwise
✓ Assignment
✓ Membership
✓ Identity
Each of these categories performs a specific task. For example, the arithmetic operators perform math-
based tasks, while relational operators perform comparisons. The following sections describe the
operators based on the category in which they appear.
Unary: -
Unary operators require a single variable or expression as input. You often use these operators as part of
a decision-making process. For example, you might want to find something that isn’t like something else.
Table shows the unary operators.
Table-Python Unary Operators
Operator Description Example
~ Inverts the bits in a number so that ~4 results in a value of –5
all the 0 bits become 1 bits and vice
versa.
- Negates the original value so that – (–4) results in 4 and 4
positive becomes negative and vice results in –4
versa.
+ Is provided purely for the sake of +4 results in a value of 4
completeness. This operator returns
the same value that you provide as
input.
Arithmetic: -
Computers are known for their capability to perform complex math. However, the complex tasks that
computers perform are often based on much simpler math tasks, such as addition. Python provides access to
libraries that help you perform complex math tasks, but you can always create your own libraries of math
functions using the simple operators found in Table.
Table-Python Arithmetic Operators
Operator Description Example
Relational: -
The relational operators compare one value to another and tell you when the relationship
you’ve provided is true. For example, 1 is less than 2, but 1 is never greater than 2. The truth
value of relations is often used to make decisions in your applications to ensure that the
condition for performing a specific task is met. Table describes the relational operators. Table-
Python Relational Operators.
Bitwise: -
The bitwise operators interact with the individual bits in a number. For
example, the number 6 is actually 0b0110 in binary.
A bitwise operator would interact with each bit within the number in a specific way.
When working with a logical bitwise operator, a value of 0 counts as false and a value of
1 counts as true.
& (And) Determines whether both individual bits 0b1100 & 0b0110
^ (Exclusive or) Determines whether just one of the individual 0b1100 ^ 0b0110 =
bits within two operators is true 0b1010
and sets the resulting bit to true when
one is. When both bits are true or both
Membership:
The membership operators detect the appearance of a value within a list or
sequence and then output the truth value of that appearance. Think of the
membership operators as you would a search routine for a database. You enter a
value that you think should appear in the database, and the search routine finds it
for you or reports that the value doesn’t exist in the database.
Table-describes the membership operators
Operator What it does
In Returns True if the specified value is present in the sequence
Not in Returns True if the specified value is not present in the sequence
The in operator is used to check if a character/substring/element exists in a sequence or not.
list1 = [1, 2, 3, 4, 5]
print(2 in list1)
print('O' in str1)
print(3 in dict1)
Output
True
False
True
The ‘not in’ Python operator evaluates to true if it does not find the variable in the specified
list1 = [1, 2, 3, 4, 5]
Output
False
True
False
Identity:
In Python, the identity operators is and is not compare the memory locations of two objects to
is: Returns True if two objects have the same memory location, or id()
is not: Returns True if two objects have different memory locations, or id()
Identity operators are used to compare the identity of objects, rather than their values.
They are different from the equality operators == and !=, which compare values.
The Python Identity Operators are used to compare the objects if both the objects are actually
of the same data type and share the same memory location. There are different identity operators such as:
Python IS Operator
The is operator evaluates to True if the variables on either side of the operator point to the same
num1 = 5
num2 = 5
a = [1, 2, 3]
b = [1, 2, 3]
c=a
s1 = "hello world"
s2 = "hello world"
# using 'is' identity operator on different datatypes
print(num1 is num2)
print(a is b)
print(a is c)
print(s1 is s2)
print(s1 is s2)
Output
True
False
True
True
True
that the variable is assigned the value ' y I. This initialization value is important, and in a
moment you will see why Line 7 is the beginning of a w h i l e loop, which starts like this:
while keep-going == ' y ' :
Notice the condition that is being tested: keep - going == y . The loop tests this condition, and
if it is true, the statements in lines 8 through 20 are executed. Then, the loop starts over at
line 7. It tests the expression keep-going == y ' and if it is true, the statements
in lines 8 through 20 are executed again. This cycle repeats until the expression keepgoing
== ' y is tested in line 7 and found to be false. When that happens, the program exits the loop.
The for loop: count controlled loop-
A count-controlled loop iterates a specific number of times. In Python you use the for
statement to write a count-controlled loop. a count-controlled loop iterates a specific number
of times. Count-controlled loops are commonly used in programs. Here is the general format:
for variable in [value 1, value2, etc.]: statement
statement etc.
We will refer to the first line as the for clause. In the f o r clause, v a r i a b l e is the name of a
variable. Inside the brackets a sequence of values appears, with a comma separating
each value. Beginning at the next line is a block of statements that is executed each time the
loop iterates.
The f o r statement executes in the following manner: The v a r i a b l e is assigned the first
value in the list, and then the statements that appear in the block are executed. Then,
v a r i a b l e is assigned the next value in the list, and the statements in the block are executed
again. This continues until v a r i a b l e has been assigned the last value in the list. Program
follows shows a simple example that uses a for loop to display the numbers 1 through 5.
# This program demonstrates a simple for loop # that uses a list of numbers.
def main ():
print ' I will display the numbers 1 through 5. ' for num in [I, 2, 3, 4, 5]:
print num # Call the main function. main ()
Program Output:
I will display the numbers 1 through 5.
1
2
3
4
5
The first time the for loop iterates, the num variable is assigned the value 1 and then the
p r i n t statement in line 7 executes (displaying the value 1). The next time the loop iterates,
num is assigned the value 2, and the p r i n t statement executes (displaying the value 2).
This process continues, until num has been assigned the last value in the list. Because the list
contains five values, the loop will iterate five times.
Python programmers commonly refer to the variable that is used in the for clause as the
target variable because it is the target of an assignment at the beginning of each loop
iteration.