Python Unit I
Python Unit I
Python
Unit – I
Introduction
Python is a fairly old language created by Guido Van Rossum. The design began in the late 1980s and was
first released in February 1991. Python is an easy to learn, powerful programming language. It has efficient
high-level data structures and a simple but effective approach to object-oriented programming. Python’s
elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for
scripting and rapid application development in many areas on most platforms.
Features of Python
Python is Interpreted − Python is processed at runtime by the interpreter. There is no need to
compile a program before executing it. This is similar to PERL and PHP.
Python is Object-Oriented − Python supports Object-Oriented style or technique of programming
that encapsulates code within objects.
Python is a Beginner's Language − Python is a great language for the beginner-level programmers
and supports the development of a wide range of applications from simple text processing to WWW
browsers to games.
Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This
allows the student to pick up the language quickly.
Easy-to-read − Python code is more clearly defined and visible to the eyes.
Easy-to-maintain − Python's source code is fairly easy-to-maintain.
A broad standard library − Python's bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
Interactive Mode − Python has support for an interactive mode which allows interactive testing and
debugging of snippets of code.
Portable − Python can run on a wide variety of hardware platforms and has the same interface on all
platforms.
Databases − Python provides interfaces to all major commercial databases.
GUI Programming − Python supports GUI applications that can be created and ported to many
system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X
Window system of Unix.
Scalable − Python provides a better structure and support for large programs than shell scripting.
Python Interpreter
An Interpreter is a program which translates the code into machine language and then executes it line by
line.
1. Interactive Mode.
2. Script Mode.
Python Shell waits for the input command from the user. As soon as the user enters the command, it
executes it and displays the result.
For example
>>> 3 + 2
5
Script Mode:
Python Shell executes a single statement. To execute multiple statements, create a Python file with
extension .py, and write Python scripts (multiple statements).
For example
Save it as myPythonScript.py
Run the file by typing python myPythonScript.py command on command prompt.
Python Indentation
Most of the programming languages like C, C++, Java use braces { } to define a block of code. Python uses
indentation. Python provides no braces to indicate blocks of code for class and function definitions or flow
control. Blocks of code are denoted by line indentation, which is rigidly enforced.
The number of spaces in the indentation is variable, but all statements within the block must be indented
the same amount. For example −
if True:
print("True")
else:
print("False")
The enforcement of indentation in Python makes the code look neat and clean. This results into Python
programs that look similar and consistent.
Python Identifiers
Identifier is the name given to entities like class, functions, variables etc. in Python. It helps differentiating
one entity from another.
Literal is a raw data given in a variable or constant. In Python, there are various types of literals they are as
follows:
Numeric Literals: Numeric Literals are immutable (unchangeable). Numeric literals can belong
to 3 different numerical types Integer, Float and Complex.
String literals: A string literal is a sequence of characters surrounded by quotes. We can use
single, double or triple quotes for a string. And, a character literal is a single
character surrounded by single or double quotes.
Boolean literals: A Boolean literal can have any of the two values: True or False.
Special literals: Python contains one special literal i.e. None. We use it to specify to that field
that is not created.
Strings:
A string is a sequence of characters. Strings are basically just a bunch of words. Strings can be created
simply by enclosing characters in quotes. Python treats single quotes the same as double quotes. Creating
strings is as simple as assigning a value to a variable.
Single Quote: Strings can be specified using single quotes such as 'Quote me on this'. All
white space i.e. spaces and tabs, within the quotes, are preserved.
Double Quotes: Strings in double quotes work exactly the same way as strings in single quotes.
An example is "What’s your name?".
Triple Quotes: Multi-line strings can specified using triple quotes - ( """ or ''' ). Single quotes
and double quotes can freely specify within the triple quotes. An example is:
'''This is a multi-line string. This is the first line.
Basics 39 This is the second line.
"What's your name?,"
I asked. He said "Bond, James Bond."
'''
Operators:
An operator is a special symbol that tells the complier to perform specific mathematical or logical operation
on one or more operands where an operand can be a variable, constant or an expression.
In Python, an operator can either be unary, binary or ternary. If an operator operates on single operand then
it is termed as unary operator. If an operator operates on two operands, it is called binary operator. The
operator that works with three operands is called ternary operator.
The various operators available in Python are
(a) Arithmetic Operators: The arithmetic operators are used for mathematical
calculations. The arithmetic operators are binary operators that work with any basic type.
Addition +
Subtraction -
Multiplication *
Division /
Modulus % this operator produces the remainder.
Exponent **
Floor Division // division that results into whole number adjusted to the left in
the number line.
For Example: Now suppose a and b are two operands of type integer then
Operation If a = 7 and b =3
a+b 10
a-b 4
a*b 21
a/b 2
a%b 1
a**b 343
a//b 2
(b) Relational Operators: The relational operators are used to check the relation between
two operands. It is used to make comparison between two operands. Relational operators are
binary operators and hence require two operands. The result of relational operation is a value that
can only be true or false according to the result of the comparison.
For Example: Now suppose a and b are two operands of type integer then
a<b False
a <= b False
a>b True
a >= b True
a == b False
a!=b True
(c) Logical Operators: Logical operators are used to combine one or more relational
expressions. In Python, there are three logical operators, logical and, logical or and logical not.
Operato
Meaning Example
r
(d) Assignment Operator: The assignment operator (=) is the most commonly used binary
operator in Python. It evaluates the operand on right hand side and then assigns the resulting
value to a variable on the left hand side. The right operand can be a variable, constant, function
call or expression.
(e) Conditional (Ternary) Operators: Ternary operators in Python are terse conditional
expressions. These are operators that test a condition and based on that, evaluate a value.
Syntax
[on_true] if [expression] else [on_false]
Python first evaluates the condition. If true, it evaluates the first expression; otherwise, it
evaluates the second.
For example:
>>> a = 8, b = 10
>>> r = “a” if a > b else “b”
>>> print( r )
(f) Bitwise Operators: Python provides extensive bit manipulation operators for programmers
who want to communicate directly with the hardware. These operators are used for testing bits or
shifting them either right to left or left to right. Following are the bitwise operators
Example
Operator Meaning Let x = 10 (0000 1010 in binary)
and y = 4 (0000 0100 in binary)
(h) Special operators: Python language offers some special type of operators like the identity
operator or the membership operator.
Identity operators: is and is not are the identity operators in Python. They are used to
check if two values (or variables) are located on the same part of the memory. Two variables
that are equal does not imply that they are identical.
Membership operators: in and not in are the membership operators in Python. They are
used to test whether a value or variable is found in a sequence
(string, list, tuple, set and dictionary).
Data types are the classification or categorization of data items. Python supports the following built-in
data types.
Scalar Types
int: Positive or negative whole numbers (without a fractional part) e.g. -10, 10, 456, 4654654.
float: Any real number with a floating-point representation in which a fractional component is
denoted by a decimal symbol or scientific notation e.g. 1.23, 3.4556789e2.
complex: A number with a real and imaginary component represented as x + 2y.
bool: Data with one of two built-in values True or False. Notice that 'T' and 'F' are
capital. true and false are not valid booleans and Python will throw an error for them.
None: The None represents the null object in Python. A None is returned by functions that don't
explicitly return a value.
Sequence Type
A sequence is an ordered collection of similar or different data types. Python has the following built-in
sequence data types:
String: A string value is a collection of one or more characters put in single, double or triple quotes.
List: A list object is an ordered collection of one or more data items, not necessarily of the same
type, put in square brackets.
Tuple: A Tuple object is an ordered collection of one or more data items, not necessarily of the same
type, put in parentheses.
Mapping Type
Set Types
set: Set is mutable, unordered collection of distinct hashable objects. The set is a Python
implementation of the set in Mathematics. A set object has suitable methods to perform
mathematical set operations like union, intersection, difference, etc.
Data objects of the above types are stored in a computer's memory for processing. Some of these
values can be modified during processing, but contents of others can't be altered once they are
created in the memory.
Comments in Python
Comments in Python are the lines in the code that are ignored by the interpreter during the execution of
the program. Comments enhance the readability of the code and help the programmers to understand the
code very carefully. There are two types of comments in Python –
Single line Comments
Multiline Comments
Single-Line Comments
Python single-line comment starts with the hashtag symbol (#) with no white spaces and lasts till the
end of the line.
For Example:
# Print “Hello World !” to console
print("Hello World")
Multi-Line Comments
Python does not provide the option for multiline comments. However, there are different ways
through which we can write multiline comments.
For Example:
For Example:
print( ): This function is used to print the data on the standard output device (Screen).
Syntax:
print(string, variable)
Example:
input( ): This function is used to take the input from the user. It returns the value in string
format. int( ) or eval( ) functions are used to convert the value into number format.
Syntax:
input([prompt])
Example:
(a) if statement (b) if-else statement (c) Nested if statement (d) if-elif-else statement
The if statement is the most simple and powerful decision control statement which is used to
control the sequence of execution of statements. It is used to execute a statement or a
statement block only if the condition is true. No statement(s) is executed when the condition
evaluates to false.
if <condition>:
statement(s)
The statement(s) must be indented at least one space to the right of the if keyword and
each statement must be indented using the same number of spaces.
The if-else statement allows the programmer to execute a statement block following the if
keyword when the condition is true and execute a different statement block following the else
keyword when the condition is false. In other words, it is a two way branching statement.
if <condition>:
statement(s)
else:
statement(s)
A nested if is an if that has another if in its if’s body or in its else’s body. The different ways
for representing nested if statements are
The if-elif-else is the most general way of writing a program involving multiple conditions.
if <condition1>:
statement1
elif <condition2>:
statement2
elif <condition3>:
statement3
else:
statement
The conditions are evaluated from the top to downward. As soon as the condition evaluates to
true, the statement associated with it is executed and the rest of the ladder is bypassed. If none
of the conditions are true, the final else gets executed.
Looping (Iteration):
The iteration (looping) statements allow a set of instructions to be performed repeatedly until a certain
condition is fulfilled. The iteration statements are also called loops or looping statements.
Python provides three kinds of loops:
For loop
While loop
The while loop is an entry-controlled loop. It means the control conditions are tested before the start of
loop’s execution. If the conditions are not satisfied then body of loop will not be executed and control will
be transferred out of the loop.
while <condition>:
# body of loop
Statement(s)
The for..in statement is another looping statement which iterates over a sequence of objects i.e. go through
each item in a sequence. A sequence is just an ordered collection of items.
For Example
Nested Loops:
Nesting of loops means one or more loop(s) within a loop. In nested loop the inner loop is executed first and
then outer. The nested loop must be used to input or output multi-dimensional array elements. In nested
loops the value of outer loop control variable will change only after the inner loop has been completely
executed.
Example: Program to print the following output
*
**
***
# Program Output
num = int(input(“Enter the Number of lines:”))
i=1
while i<=num :
j=1
while j<=I :
print(“*”)
j = j +1
i=i+1
print( )
The continue is another jump statement like the break statement as both the statements skip over a part of
the code. But the continue statement is somewhat different from break. Instead of forcing termination, it
forces the next iteration of the loop to take place, skipping any code in between.
Example:
1. var = 10
2. while var > 0:
3. var = var - 1
4. if var == 5
5. contine
6. print(“Current variable value:”, var)
7. print(“Good Bye!”)
Example:
range function:
The Python range() function returns the sequence of the given number between the given range.
Syntax
range(start, stop, step)
Parameter
Paramete Description
r
stop Required. An integer number specifying at which position to stop (not included).
Example:
x = range(3, 20, 2)
for n in x:
print(n)