0% found this document useful (0 votes)
3 views21 pages

Bcaty Unit-1 Python Notes Modified

Python is a high-level, interpreted programming language created by Guido van Rossum in 1991, emphasizing code readability and efficiency. It features object-oriented and functional programming capabilities, dynamic typing, automatic memory management, and a rich set of built-in data types and libraries. Python is versatile, used in various domains such as web development, systems programming, database programming, and scientific computing.

Uploaded by

nmscompdept
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
3 views21 pages

Bcaty Unit-1 Python Notes Modified

Python is a high-level, interpreted programming language created by Guido van Rossum in 1991, emphasizing code readability and efficiency. It features object-oriented and functional programming capabilities, dynamic typing, automatic memory management, and a rich set of built-in data types and libraries. Python is versatile, used in various domains such as web development, systems programming, database programming, and scientific computing.

Uploaded by

nmscompdept
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 21

UNIT –I

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

DATA TYPES IN PYTHON:


Python has six standard Data Types: -
 Numeric
 String
 List
 Tuple
 Set
 Dictionary

Numeric Data Type: -


In Python, numeric data type represents the data that has a numeric value. The numeric
value can be an integer, floating number, or even complex number. These values are
defined as int, float, and complex classes in Python.
Integers – This data type is represented with the help of int class. It consists of positive or negative
whole numbers (without fraction or decimal). In Python, there’s no limit to how long integer values are
often.
Example: -
a=2
print (a, "is of type", type(a))
Output: 2 is of type <class ‘integer’>
Float – This type is represented by the float class. It is a true number with floating-point
representation. It is specified by a decimal point. Optionally, the character e or E followed by a positive
or negative integer could even be appended to specify scientific notation.
Example: -
b = 1.5
print (b, "is of type", type(b))
Output: 1.5 is of type <class ‘float’>
Complex Numbers – Complex numbers are represented by complex classes. It is
specified as (real part) + (imaginary part) j, For example – 4+5j.
Example: -
c = 8+3j
print (c, "is a type", type(c))
Output: (8+3j) is a type <class’complex’>
String Data Type: -
The string is a sequence of Unicode characters. A string may be a collection of 1 or more
characters put during a quotation mark, double-quote, or triple quote. It can be
represented using an str class.
Example: -
string1= “Hello World”
print(string1)
output: Hello World
We can perform several operations in strings like Concatenation, Slicing, and Repetition.
Concatenation: It includes the operation of joining two or more strings together.
Example: -
String1 = "Hello"
String2 ="World"
print(String1+String2)
Output: Hello World
Slicing: Slicing is a technique for extracting different parts of a string.
Example: -
String1 = "Hello"
print(String1[2:5])
Output: llo
Repetition:
It means repeating a sequence of instructions a certain number of times.
Example: -
Print(String1*5)
Output: HelloHelloHelloHelloHello
List Data Type: -
A list is formed (or created) by placing all the items (elements) inside square brackets [ ],
separated by commas. It can have any number of items and they may or may not be of
different types (integer, float, string, etc.). A list is mutable, which suggests we will modify the list
Example:
List1 = [3,8,7.2,"Hello"]
print("List1[2] = ", List [2])
Output: List1[2] = 7.2
print("List1[1:3] = ", List [1:3])
Output: List1[1:3] = [8, 7.2]
Updating the list: - we can update the list.
List1[3] = "World"
#If we print the whole list, we can see the updated list.
print(List1)
Output: [3, 8, 7.2, ‘World’]
Tuple Data Type: -
A tuple is defined as an ordered collection of Python objects. The only difference between tuple and list
is that tuples are immutable i.e. tuples can’t be modified after it’s created. It is represented by tuple
class. we can represent tuples using parentheses ( ).
Example:
Tuple = (25,10,12.5,"Hello")
print("Tuple[1] = ", Tuple[1])
Output: Tuple[1] = 10
print("Tuple[0:3] =", Tuple[0:3])
Output: Tuple[0:3] = (25,10,12.5)
Set Data Type: -
A set is an unordered collection of items. Every set element is exclusive (no duplicates) and must be
immutable (cannot be changed).
Example:
Set = {4,3,6.6,"Hello"}
print(Set)
Output: {‘Hello’, 3, 4, 6.6}
As the set is an unordered collection, indexing will be meaningless. Hence the slicing
operator [ ] doesn’t work.
Set[1] = 12
Output: TypeError
Dictionary Data Type: -
In Python, Dictionary is an unordered collection of data values, which is used to store data values like a
map, which, unlike other Data Types that hold only a single value as an
element, a Dictionary consists of key-value pair. Key-value is provided within the dictionary to form it
more optimized. In the representation of a dictionary data type, each
key-value pair during a Dictionary is separated by a colon: whereas each key’s separated by a ‘comma’.
Syntax:
Key:value
Example:
Dict1 = {1:'Hello',2:5.5, 3:'World'}
print(Dict1)
Output: {1: ‘Hello’, 2: 5.5, 3: ‘World’}
We can retrieve the value by using the following method:
Example:
print(Dict[2])
Output: 5.5
We can update the dictionary by following methods as well:
Example:
Dict[3] = 'World'
print(Dict)
Output:
{1: ‘Hello’, 2: 5.5, 3: ‘World’}
Comments: -
CONCEPT: Comments are notes of explanation that document lines or sections of a
program. Comments are part of the program, but the Python interpreter ignores them.
They are intended for people who may be reading the Source code. Comments are short notes placed in
different parts of a program, explaining how those parts of the program work. Although comments are a
critical part of a program, they are ignored by the Python interpreter. Comments are intended for any
person reading a program's code, not the computer.
In Python you begin a comment with the # character. When the Python interpreter sees a #
character, it ignores everything from that character to the end of the line. For example, look
at Program. Lines 1 and 2 are comments that briefly explain the program's purpose.
Program 1 (comment1 .py)
1 # This program displays a person's
2 # name and address.
3 print 'Kate Austen'
4 print ' 123 Dharma Lane'
5 print 'Asheville, NC 28899'
Program Output
Kate Austen
123 Dharma Lane
Asheville, NC ,28899
Programmers commonly write end-line comments in their code. An end-line comment is a comment
that appears at the end of a line of code. It usually explains the statement that appears in that line.
Program shows an example. Each line ends with a comment that briefly explains what the line does.
1. print "Kate Austen" # Display the name
2 print "123 Dharma Lane" # Display the street address
3 print "Asheville, NC 28899" # Display the city, state, and ZIP
Program Output
Kate Austen
123 Dharma Lane
Asheville, NC 28899
Variables CONCEPT:
A variable is a name that represents a value stored in the computer's memory. Programs use
variables to access and manipulate data that is stored in memory.
When a variable represents a value in the computer's memory, we say that the variable references the
value.
Creating Variables with Assignment Statements:
You use an assignment statement to create a variable in Python.
Here is an example of an assignment statement: age = 25 after this statement executes, a variable named age
will be created and it will reference the value 25.
An assignment statement is written in the following general format:
variable = expression
The equal sign (=) is known as the assignment operator. In the general format, variable is
the name of a variable and expression is a value, or any piece of code that results in a value.
After an assignment statement executes, the variable listed on the left side of the = operator
will reference the value given on the right side of the = operator.
In an assignment statement, the variable that is receiving the assignment must appear on
the left side of the = operator. For example, the following statement will cause an error:
25 = age # This is an error!
You cannot use a variable until you have assigned a value to it. An error will occur if you try to perform an
operation on a variable, such as printing it, before it has been assigned a value. Sometimes a simple typing
mistake will cause this error.
The code in following Program demonstrates a variable. Line 2 creates a variable named room
and assigns it the value 503. The p r i n t statements in lines 3 and 4 display a message.
Notice that line 4 displays the value that is referenced by the room variable.
Program (variable-demo.py)
I # This program demonstrates a variable.
2 room = 503
3 print 'I am staying in room number'
4 print room
Program Output
I room number
503
Notice that in line 4 there are no quotation marks around room. If quotation marks were
placed around room, it would have indicated that we want to display the word "room"
instead of the contents of the room variable. In other words, the following statement will
display the contents of the room variable:
print room
This statement, however, will display the word "age":
print 'age'
Program shows a sample program that uses two variables. Line 2 creates a variable named top speed,
assigning it the value 160. Line 3 creates a variable named distance, assigning it. The value 300.
# Create two variables: top-speed and distance.
top-speed = 160
distance = 300
# Display the values referenced by the variables.
print 'The top speed is'
print top-speed
print ' The distance travelled is '
print distance
Program Output
The top speed is
16 0
The distance travelled is
300
you must follow these rules:
1. You cannot use one of Python's key words as a variable name.
2. A variable name cannot contain spaces.
3.The first character must be one of the letters a through z, A through Z, or an underscore
character (-). After the first character you may use the letters a through z or A through 2,the digits O
through 9, or underscores.
4.Uppercase and lowercase characters are distinct. This means the variable name Itemsordered is not
the same as itemsordered.

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

+ Adds two values together 5+2=7


- Subtracts the right operand from 5–2=3
the left operand
* Multiplies the right operand by 5 * 2 = 10
the left operand
/ Divides the left operand by the right operand 5 / 2 = 2.5
% Divides the left operand by the right operand
And returns the remainder 5%2=1
** Calculates the exponential value of the right
Operand by the left operand 5 ** 2 = 25
// performs integer division, in which the left operand
is divided by the right operand and only the whole
number is returned (also called floor division) 5 // 2 = 2.

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.

Operator Description Example


== Determines whether two values are equal. 1 == 2 is False
Notice that the relational operator uses
two equals signs. A mistake many developers make
is using just one equals sign, which results in one
value being assigned to another.
!= Determines whether two values are not equal. 1! = 2 is True
Some older versions of Python allowed you to use
the <> operator in place of the! = operator. Using
the <> operator results in an error in current versions
of Python.
> Verifies that the left operand value is greater than the 1 > 2 is False right
operand value.
< Verifies that the left operand value is less than the right 1<2 is True
operand value.
>= Verifies that the left operand value is greater than or
equal to the right operand value. 1>=2 is
False
<= Verifies that the left operand value is less than or equal
to the right operand value. 1<=2 is
True
Logical
The logical operators combine the true or false value of variables or expressions so that
you can determine their resultant truth value. You use the logical operators to create
Boolean expressions that help determine whether to perform tasks. Table describes the
logical operators. Table Python Logical Operators
Operator Description Example
and Determines whether both operands True and True is
True are true. True and False is
False
False and True is False
False and False is False
or Determines when one of two operands True or True is
True is true. True or False is
True
False or True is True
False or False is False
not Negates the truth value of a single not True is
False operand. A true value becomes false not False
is True and a false value becomes true.

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.

Table-describes the bitwise operators.


Operator Description Example

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

bits are false, the result is false.


~ (One’s complement) Calculates the one’s complement value ~0b1100 =
of a number. –0b1101
~0b0110 =
–0b0111
<< (Left shift) Shifts the bits in the left operand left by 0b00110011 << 2 =
the value of the right operand. All new 0b11001100
bits are set to 0 and all bits that flow off
the end is lost.
>> (Right shift) Shifts the bits in the left operand right by 0b00110011 >> 2 =
the value of the right operand. All new 0b00001100
bits are set to 0 and all bits that flow off the end
is lost.

within two operators are true and sets = 0b0100

the resulting bit to true when they are.

| (Or) Determines whether either of the individual 0b1100 | 0b0110 =

bits within two operators is true 0b1110

and sets the resulting bit to true when

one of them is.


Assignment:
The assignment operators place data within a variable. The simple assignment
operator appears in previous chapters of the book, but Python offers a number of
other interesting assignment operators that you can use. These other assignment
operators can perform mathematical tasks during the assignment process, which
makes it possible to combine assignment with a math operation. Table describes the
assignment operators. For this particular table, the initial value of MyVar in the
Example column is 5.
Operator Description Example
= Assigns the value found in the MyVar = 2 results
in right operand to the left operand. MyVar containing 2
+= Adds the value found in the right operand MyVar += 2 results
to the value found in the left operand and in MyVar containing
7 places the result in the left operand.
-= Subtracts the value found in the right MyVar -= 2 results
operand from the value found in the left in MyVar containing 3
operand and places the result in the left
operand.
*= Multiplies the value found in the right operand MyVar *= 2 results
by the value found in the left operand in MyVar containing 10
and places the result in the left operand.
/= Divides the value found in the left operand MyVar /= 2 results by
the value found in the right operand and in MyVar containing
places the result in the left operand. 2.5
%= Divides the value found in the left operand MyVar %= 2 results
by the value found in the right operand and in MyVar containing
places the remainder in the left operand. 1
**= Determines the exponential value found in MyVar **= 2 results
the left operand when raised to the power in MyVar containing
of the value found in the right operand and 25
places the result in the left operand.
//= Divides the value found in the left operand MyVar //= 2 results
by the value found in the right operand and in MyVar containing
Access the integer (whole number) result in 2
the left operand.

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.

Evaluate to True if it finds the specified element in a sequence otherwise False.

# initialized some sequences

list1 = [1, 2, 3, 4, 5]

str1 = "Hello World"

dict1 = {1: "Geeks", 2:"for", 3:"geeks"}

# using membership 'in' operator

# checking an integer in a list

print(2 in list1)

# checking a character in a string

print('O' in str1)

# checking for a key in a dictionary

print(3 in dict1)

Output

True

False

True

Python NOT IN Operator:

The ‘not in’ Python operator evaluates to true if it does not find the variable in the specified

sequence and false otherwise.

# initialized some sequences

list1 = [1, 2, 3, 4, 5]

str1 = "Hello World"

dict1 = {1: "Geeks", 2:"for", 3:"geeks"}

# using membership 'not in' operator

# checking an integer in a list

print(2 not in list1)

# checking a character in a string


print('O' not in str1)

# checking for a key in a dictionary

print(3 not in dict1)

Output

False

True

False

Identity:

In Python, the identity operators is and is not compare the memory locations of two objects to

determine if they are the same:

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

object in the memory and false otherwise.

# Python program to illustrate the use

# of 'is' identity operator

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

Python IS NOT Operator:


The is not operator evaluates True if both variables on the either side of the operator are not
the same object in the memory location otherwise it evaluates False.
# Python program to illustrate the use
# of 'is' identity operator
num1 = 5
num2 = 5
a = [1, 2, 3]
b = [1, 2, 3]
c=a
s1 = "hello world"
s2 = "hello world"
# using 'is not' identity operator on different datatypes
print(num1 is not num2)
print(a is not b)
print(a is not c)
print(s1 is not s2)
print(s1 is not s1)
Output
False
True
False
False
False
Control Structures: -
Making Simple Decisions Using the if Statement:
The if statement is the easiest method for making a decision in Python. It simply states that if
something is true, Python should perform the steps that follow.
In simple terms, the Python if statement selects actions to perform. Along with its expression
counterpart, it’s the primary selection tool in Python and represents much
of the logic a Python program possesses. In a decision structure's simplest form, a specific
action is performed only if a certain condition exists. If the condition does not exist, the
action is not performed.
In Python we use the if statement to write a single alternative decision structure. Here is the
general format of the if statement:
if condition:
Statement
statement
etc.
For simplicity, we will refer to the first line as the if clause. The if clause begins with the word
if , followed by a condition, which is an expression that will be evaluated as either true or
false. A colon appears after the condition. Beginning at the next line is a block of statements.
(Note that all of the statements in a block must be consistently indented.
This indentation is required because the Python interpreter uses it to tell where the block
begins and ends.)
When the if statement executes, the condition is tested. If the condition is true, the
statements that appear in the block following the if clause are executed. If the condition is
false, the statements in the block are skipped.
Let's look at the following example of the if statement:
if sales > 50000:
bonus = 500.0
This statement uses the > operator to determine whether sales is greater than 50,000. If the
expression sales > 50000 is true, the variable bonus is assigned 500.0. If the expression is
false, however, the assignment statement is skipped.
The if-else Statement:
An if -else statement will execute one block of statements if its condition is true, or another
block if its condition is false.
In code we write a dual alternative decision structure as an i f -else statement. Here is the
general format of the if-else statement:
if condition:
statement statement etc.
else:
statement statement
etc.
When this statement executes, the condition is tested. If it is true, the block of indented
statements following the i f clause is executed, and then control of the program jumps to the
statement that follows the if-else statement. If the condition is false, the block of indented
statements following the else clause is executed, and then control of the program jumps to
the statement that follows the if-else statement.
The following code shows an example of an if -else statement.
if temperature < 40:
print "A little cold, isn't it?"
else:
print "Nice weather we're having."
Indentation in the if-else Statements:
When you write an if -else statement, follow these guidelines for indentation:
Make sure the if clause and the else clause are aligned.
The if clause and the else clause are each followed by a block of statements. Make ' sure the
statements in the blocks are consistently indented.
Nested Decision control structures:
To test more than one condition, a decision structure can be nested inside another decision
structure.
You can also nest decision structures inside other decision structures. In fact, this is a
common requirement in programs that need to test more than one condition. For example,
consider a program that determines whether a bank customer qualifies for a loan.
To qualify, two conditions must exist:
(1) the customer must earn at least $30,000 per year, and
(2) the customer must have been employed at his or her current job for at least two years.
Assume that the salary variable is assigned the customer's annual salary, and the years on job
variable is assigned the number of years that the customer has worked on his or her current
job.
If we follow the flow of execution, we see that the condition salary >= 30000 is tested.
If this condition is false, there is no need to perform further tests; we know that the customer
does not qualify for the loan. If the condition is true, however, we need to test the second
condition. This is done with a nested decision structure that tests the condition years on job
>= 2. If this condition is true, then the customer qualifies for the loan.
If this condition is false, then the customer does not qualify.
#This program determines whether a bank customer qualifies for a loan.
def main ( ) :
# Get the customer's annual salary.
salary = input ( 'Enter your annual salary: ' )
# Get the number of years on the current job.
years-on-job = input('Enter the number of ' + \'years on your current job: ')
# Determine whether the customer qualifies.
if salary >= 30000.0:
if years-on-job >= 2:
print ' You qualify for the loan. '
else:
print 'You must have been on your current' print 'job for at least two years to
qualify. '
else:
print 'You must earn at least $30,000 per year' print 'to qualify. '
# Call the main function.
main'( )
if-elif-else statement:
The logic of the nested decision structure is fairly complex. Python provides a special version
of the decision structure known as the i f- elif -else statement, which makes this type of logic
simpler to write. Here is the general format of the if -elif -else statement:
if condition-1 :
statement statement etc.
elif condition-2 :
statement statement etc.
Insert as many elif clauses as necessary
else:
statement statement etc.
When the statement executes, c o n d i t i o n- 1 is tested. If c o n d i t i o n- 1 is true, the block
of statements that immediately follow is executed, up to the elif clause. The rest of the
structure is ignored. If condition-1 is false, however, the program jumps to the very next elif
clause and tests condition 2. If it is true, the block of statements that immediately follow is
executed, up to the next elif clause. The rest the structure is then ignored. This process
continues until a condition is found to be true, or no more elif clauses are left. If no condition
is true, the block of statements following the else clause is executed.
The following is an example of the i f -elif - else statement.
i f score < 60:
p r i n t 'Your grade is F. '
elif score < 70:
p r i n t 'Your grade is D. '
elif score < 80:
p r i n t 'Your grade is C. '
elif score < 90:
p r i n t 'Your grade is B. '
else :
p r i n t 'Your grade is A. '
Repetition Structures: -
- CONCEPT: A repetition structure causes a statement or set of statements to execute
repeatedly.
Programmers commonly have to write code that perform the same task over and over.
As you can see, this code is one long sequence structure containing a lot of duplicated code.
There are several disadvantages to this approach, including the following:
-The duplicated code makes the program large.
-Writing a long sequence of statements can be time consuming.
-If part of the duplicated code has to be corrected or changed then the correction or change
has to be done many times.
Instead of writing the same sequence of statements over and over, a better way to repeatedly
perform an operation is to write the code for the operation once, and then place that code in a
structure that makes the computer repeat it as many times as necessary.
This can be done with a repetition structure, which is more commonly known as a loop.
Condition Controlled and count-controlled loops: -
A condition-controlled loop uses a true/false condition to control the number of times that it
repeats. A count-controlled loop repeats a specific number of times.
In Python you use the w h i l e statement to write a condition-controlled loop, and you use the
for statement to write a count-controlled loop.
The While-loop: a condition controlled: -
CONCEPT: A condition-controlled loop causes a statement or set of statements to repeat as
long as a condition is true. In Python you use the while statement to write a condition-
controlled loop.
The while loop gets its name from the way it works: while a condition is true, do some task.
The loop has two parts: (1) a condition that is tested for a true or false value, and
(2) a statement or set of statements that is repeated as long as the condition is true. Here is
the general format of the while loop in Python:
while condition:
statement statement etc.
For simplicity, we will refer to the first line as the while clause. The while clause begins
*with the word while, followed by a Boolean condition that will be evaluated as either true or
false. A colon appears after the condition. Beginning at the next line is a block of statements.
When the while loop executes, the condition is tested. If the condition is true, the statements
that appear in the block following the while clause are executed, and then the loop starts
over. If the condition is false, the program exits the loop.
Program following shows how we might use a while loop to write the commission calculating
program.
1.# This program calculates sales commissions.
2 def main ():
3 # Create a variable to control the loop.
4 keep-going = ' y ' 5
6 # Calculate a series of commissions.
7 while keep-going == 'y':
8 # Get a salesperson's sales and commission rate.
9 sales = input (‘Enter the amount of sales: ‘)
10 comm-rate = input ('Enter the commission rate: ') 13
32 # Calculate the commission.
13 commission = sales * comm-rate 14
15 # Display the commission.
16 print 'The commission is $%.2f.' % commission 17
18 # See if the user wants to do another one.
19 keep-going = raw-input (‘Do you want to calculate another ' + \ 2 0 'commission
(Enter y for yes): ‘)
21
22 # Call the main function.
23 main ()
In line 4 we use an assignment statement to create a variable named keep- g oing. Notice

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.

You might also like