0% found this document useful (0 votes)
2 views

Python Unit I

The document provides an introduction to Python, detailing its history, features, and various programming concepts such as indentation, identifiers, literals, operators, data types, comments, and input/output statements. It emphasizes Python's ease of learning and versatility for beginners while outlining the structure and syntax unique to the language. Additionally, it explains the use of the Python interpreter in both interactive and script modes.

Uploaded by

nimodbd
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python Unit I

The document provides an introduction to Python, detailing its history, features, and various programming concepts such as indentation, identifiers, literals, operators, data types, comments, and input/output statements. It emphasizes Python's ease of learning and versatility for beginners while outlining the structure and syntax unique to the language. Additionally, it explains the use of the Python interpreter in both interactive and script modes.

Uploaded by

nimodbd
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

BCA IInd Year

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.

Python Interpreter is used in two modes:

1. Interactive Mode.
2. Script Mode.

Interactive Mode (Python Shell):


Python interpreter in interactive mode is commonly known as Python Shell. Python provides a
Python Shell (also known as Python Interactive Shell) which is used to execute a single Python
command and get the result.

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.

To open the Python Shell on Windows


 Open the command prompt
 Write python and press enter key.
 A Python Prompt comprising of three greater than symbols (>>>) appears.
 Now user can enter a single statement and get 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

 Enter the following statement in a text editor such as Notepad.

print ("This is Python Script.")


print ("Welcome to Python Tutorial by TutorialsTeacher.com")

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

Rules for writing identifiers


1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to
9) or an underscore (_). Names like myClass, var_1 and print_this_to_screen, all are valid example.
2. An identifier cannot start with a digit. 1variable is invalid, but variable1 is perfectly fine.
3. Keywords cannot be used as identifiers.
4. We cannot use special symbols like !, @, #, $, % etc. in our identifier.
5. Identifier can be of any length.

Reserved Words (Keywords)


The following list shows the Python keywords. These are reserved words and cannot use as constant or
variable or any other identifier names. There are 33 keywords in Python. All the Python keywords contain
lowercase letters only.

and Exec not continue raise

assert Finally or def return

break For pass del try

class From print elif while


Literals:

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.

There are six relational operators

Less than <


Less than or equal to <=
Greater than >
Greater than or equal to >=
Equal to ==
Not equal to !=

For Example: Now suppose a and b are two operands of type integer then

Operation Result (If a = 7 and b =3)

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

and True if both the operands are true x and y

or True if either of the operands is true x or y

not True if operand is false (complements the operand) not x

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

variable = expression/constant/function call


Example: a=3
x = y + 10

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

& Bitwise AND x & y = 0 (0000 0000)

| Bitwise OR x | y = 14 (0000 1110)


~ Bitwise NOT ~x = -11 (1111 0101)

Λ Bitwise XOR x Λ y = 14 (0000 1110)

>> Bitwise Right Shift x >> 2 = 2 (0000 0010)

<< Bitwise Left Shift x << 2 = 40 (0010 1000)

(g) Increment (++) and Decrement (--) Operator:


In certain situations, there is a need to increase or decrease the value of an operand by 1. Python
provides an increment operator (++) and a decrement operator (--) to increase and decrease the
value of the operand by 1 respectively.
If x is a variable then x++ is equivalent to x = x + 1. This means that value of a variable x is
increased by 1. Similarly, x-- is equivalent to x = x – 1. This means that value of a variable x is
decreased by 1.

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

Operator Meaning Example

True if the operands are identical (refer to the same


is x is True
object)

True if the operands are not identical (do not refer to


is not x is not True
the same object)

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

Operator Meaning Example

in True if value/variable is found in the sequence 5 in x

not in True if value/variable is not found in the sequence 5 not in x


Python Data Types

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

Dictionary: A dictionary Dict() object is an unordered collection of data in a key:value pair


form. A collection of such pairs is enclosed in curly brackets. For example: {1:"Steve",
2:"Bill"}

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.

Mutable and Immutable Types

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.

 Using Multiple Hashtags (#)


Multiple hashtags (#) can be used to write multiline comments in Python. Each and every
will be considered as a single-line comment.

For Example:

# Python program to demonstrate


# multiline comments
print("Multiline comments")

 Using String Literals


Python ignores the string literals that are not assigned to a variable so we can use these
string literals as a comment. So we use the strings with triple quotes (“””) as multiline
comments.

For Example:

""" Python program to demonstrate


multiline comments"""
print("Multiline comments")

Input and Output Statements:


The functions like input( ) and print( ) are widely used for standard input and output operations
respectively.

print( ): This function is used to print the data on the standard output device (Screen).

Syntax:

print(string, variable)

Example:

1. print(“This sentence is output to the screen”)


2. # Output: This sentence is output to the screen
3.
4. a = 5
5.
6. print(“The value of a is”, a)
7. # Output: The value of a is 5

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

Here prompt is the string display it on the screen. It is optional;

Example:

>>> num = input(“'Enter a number: “)


Enter a number: 10
>>> num
“10”

Selection or Decision Control Statements:


The selection statement means the execution of statement(s) depending upon a condition-test. If a condition
evaluates to true, a course-of-action (a set of statements) is followed otherwise another course-of-action (a
different set of statements) is followed. This selection statement is also called decision control statement
because it helps in making decision about which set-of-statements is to be executed.

The following decision control statements are supported by Python

(a) if statement (b) if-else statement (c) Nested if statement (d) if-elif-else statement

(a) Simple If 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.

The general form is:

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.

Example: To check if a number is greater than 25.


1. a = int(input(”Enter a number : ”))
2.
3. if a > 25:
4. print(“Number is greater than 25”)

(b) The If-else statement:

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.

The general form is:

if <condition>:
statement(s)
else:
statement(s)

Example: To check whether a given number is odd or even.

1. a = int(input(”Enter a number : ”))


2.
3. if a % 2 == 0:
4. print(“Number is Even”)
5. else:
6. print(“Number is Odd”)

(c) Nested If statement:

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

if <condition1>: | if <condition1>: | if <condition1>:


if <condition2>: | if <condition2>: | statement1
statement1 | statement1 | else:
else: | else: | if <condition2>:
statement2 | statement2 | statement2
else: | else: | else:
statement3 | if <condition3>: | statement3
| statement3 |
| else: |
| statement4 |

In an if statement, either there can be if statement(s) in its body-of-if or in its body-of-else or in


both.

Example: To calculate the greatest of three numbers.

1. a = int(input(”Enter a number : ”))


2. b = int(input(”Enter a number : ”))
3. c = int(input(”Enter a number : ”))
4.
5. if a > b:
6. if a > c:
7. print(“A is greater”)
8. else:
9. print(“C is greater”)
10. else:
11. if b > c:
12. print(“B is greater”)
13. else:
14. print(“C is greater”)

(d) The if-elif-else Statement:

The if-elif-else is the most general way of writing a program involving multiple conditions.

The general form is

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.

Example: To calculate the greatest of three numbers.

1. a = int(input(”Enter a number : ”))


2. b = int(input(”Enter a number : ”))
3. c = int(input(”Enter a number : ”))
4.
5. if a > b and a > c:
6. print(“A is greater”)
7. elif a > b and b > c:
8. print(“B is greater”)
9. else:
10. print(“C is greater”)

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

(1) The 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.

The syntax of a while loop is

while <condition>:
# body of loop
Statement(s)

Example: Program to calculate the factorial of an entered number.

1. a = int(input(”Enter a number : ”))


2. fact = 1
3. while a > 0:
4. fact = fact * a
5. a=a–1
6. print(“The factorial of given number is :”, fact)

(2) The for loop:

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.

The syntax of a for loop is

for iterating_var in sequence:


statements(s)

For Example

for letter in 'Python': # First Example


print('Current Letter :', letter)

fruits = ['banana', 'apple', 'mango']


for fruit in fruits: # Second Example
print('Current fruit :', fruit)

print "Good bye!"

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 break Statement:


The break statement enables a program to skip over part of the code. A break statement terminates the
smallest enclosing while or for statement. Execution resumes at the statement immediately following the
body of the terminated statement.

Example: To stop the countdown before its natural end


1. print(“Program for Break Statement”)
2. for n in range(0, 10):
3. if n == 3:
4. print(“Countdown aborted!”)
5. break

The continue Statement:

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!”)

The pass Statement:


The pass keyword as name suggests, does nothing. It is used as a dummy place holder whenever a
syntactical requirement of a certain programming element is to be fulfilled without assigning any operation.
In other words, the pass statement is simply ignored by the Python interpreter and can be seen as a null
statement. It is generally used as a dummy statement in a code block.

Example:

for num in range(1,6):


if num==3:
pass
else:
print ("Num = “, num)

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

start Optional. An integer number specifying at which position to start. Default is 0

stop Required. An integer number specifying at which position to stop (not included).

step Optional. An integer number specifying the incrementation. Default is 1

Example:

x = range(3, 20, 2)
for n in x:
print(n)

You might also like