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

Unit1 PythonNotes

Uploaded by

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

Unit1 PythonNotes

Uploaded by

Barani Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Python Programming-Unit-1 Notes

What is Python?
Python is a general purpose, dynamic, high-level, and interpreted programming
language. It supports Object Oriented programming approach to develop
applications. It is simple and easy to learn and provides lots of high-level data
structures.

Python is easy to learn yet powerful and versatile scripting language, which makes it
attractive for Application Development.

Python History
Python was invented by Guido van Rossum in 1991 at CWI in Netherland. The idea
of Python programming language has taken from the ABC programming language
or we can say that ABC is a predecessor of Python language.

There is also a fact behind the choosing name Python. Guido van Rossum was a fan
of the popular BBC comedy show of that time, "Monty Python's Flying Circus". So
he decided to pick the name Python for his newly created programming language.

Python Features
Python provides many useful features which make it popular and valuable from the
other programming languages. It supports object-oriented programming, procedural
programming approaches and provides dynamic memory allocation. We have listed
below a few essential features.

1) Easy to Learn and Use


Python is easy to learn as compared to other programming languages. Its syntax is
straightforward and much the same as the English language. There is no use of the
semicolon or curly-bracket, the indentation defines the code block. It is the
recommended programming language for beginners.
2) Expressive Language
Python can perform complex tasks using a few lines of code. A simple example, the
hello world program you simply type print("Hello World"). It will take only one line
to execute, while Java or C takes multiple lines.

3) Interpreted Language
Python is an interpreted language; it means the Python program is executed one line
at a time. The advantage of being interpreted language, it makes debugging easy
and portable.

4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, UNIX, and
Macintosh, etc. So, we can say that Python is a portable language. It enables
programmers to develop the software for several competing platforms by writing a
program only once.

5) Free and Open Source


Python is freely available for everyone. It is freely available on its official
website www.python.org. It has a large community across the world that is
dedicatedly working towards make new python modules and functions. Anyone can
contribute to the Python community. The open-source means, "Anyone can
download its source code without paying any penny."

C++ vs Java

6) Object-Oriented Language
Python supports object-oriented language and concepts of classes and objects come
into existence. It supports inheritance, polymorphism, and encapsulation, etc. The
object-oriented procedure helps to programmer to write reusable code and develop
applications in less code.

7) Extensible
It implies that other languages such as C/C++ can be used to compile the code and
thus it can be used further in our Python code. It converts the program into byte
code, and any platform can use that byte code.
8) Large Standard Library
It provides a vast range of libraries for the various fields such as machine learning,
web developer, and also for the scripting. There are various machine learning
libraries, such as Tensor flow, Pandas, Numpy, Keras, and Pytorch, etc. Django, flask,
pyramids are the popular framework for Python web development.

9) GUI Programming Support


Graphical User Interface is used for the developing Desktop application. PyQT5,
Tkinter, Kivy are the libraries which are used for developing the web application.

10) Integrated
It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs
code line by line like C,C++ Java. It makes easy to debug the code.

11. Embeddable
The code of the other programming language can use in the Python source code. We
can use Python source code in another programming language as well. It can embed
other language into our code.

12. Dynamic Memory Allocation


In Python, we don't need to specify the data-type of the variable. When we assign
some value to the variable, it automatically allocates the memory to the variable at
run time. Suppose we are assigned integer value 15 to x, then we don't need to
write int x = 15. Just write x = 15.

Python Applications
Python is known for its general-purpose nature that makes it applicable in almost
every domain of software development. Python makes its presence in every
emerging field. It is the fastest-growing programming language and can develop any
application.

Here, specifying application areas where Python can be applied.


Python is a general-purpose, popular programming language and it is used in almost
every technical field. The various areas of Python use are given below.

o Data Science
o Date Mining
o Desktop Applications
o Console-based Applications
o Mobile Applications
o Software Development
o Artificial Intelligence
o Web Applications
o Enterprise Applications
o 3D CAD Applications
o Machine Learning
o Computer Vision or Image Processing Applications.
o Speech Recognitions

Setting up PATH
Windows Installation
Here are the steps to install Python on Windows machine.
 Open a Web browser and go to https://www.python.org/downloads/

Setting path at Windows


To add the Python directory to the path for a particular session in Windows −
At the command prompt − type path %path%;C:\Python and press Enter.

C:\Python is the path of the Python directory

Python - Basic Syntax


First Python Program
Let us execute programs in different modes of programming.
Interactive Mode Programming
Invoking the interpreter without passing a script file as a parameter brings up the
following prompt −
$ python
Python 2.4.3 (#1, Nov 11 2010, 13:34:43)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more
information.
>>>
Type the following text at the Python prompt and press the Enter −
>>> print "Hello, Python!"

Script Mode Programming


Let us write a simple Python program in a script. Python files have extension .py.
Type the following source code in a test.py file −
$ python test.py
This produces the following result −
Hello, Python!
Lines and 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"

Comments in Python
A hash sign (#) that is not inside a string literal begins a comment. All characters
after the # and up to the end of the physical line are part of the comment and the
Python interpreter ignores them.

# First comment
print "Hello, Python!" # second comment
Following triple-quoted string is also ignored by Python interpreter and can be used
as a multiline comments:
'''
This is a multiline
comment.
'''

Python Variables
Variable is a name that is used to refer to memory location. Python variable is also
known as an identifier and used to hold value.

Variables are containers for storing data values.

In Python, we don't need to specify the type of variable because Python is a infer
language and smart enough to get variable type.

Variable names can be a group of both the letters and digits, but they have to begin
with a letter or an underscore.

Variable Names
A variable can have a short name (like x and y) or a more descriptive name
(age, carname, total_volume). Rules for Python variables:
 A variable name must start with a letter or the underscore character
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
 Variable names are case-sensitive (age, Age and AGE are three
different variables)

Creating Variables
Python has no command for declaring a variable.

A variable is created the moment you first assign a value to it.

Example
x = 5
y = "SAC"
print(x)
print(y)

Get the Type


You can get the data type of a variable with the type() function.

Example
x = 5
y = "John"
print(type(x))
print(type(y))

Python Keywords
Python Keywords are special reserved words that convey a special meaning to the
compiler/interpreter. Each keyword has a special meaning and a specific operation.
These keywords can't be used as a variable. Following is the List of Python Keywords.

True False None and as

asset def class continue break


else finally elif del except

global for if from import

raise try or return pass

nonlocal in not is lambda

Python Data Types


Data types are the classification or categorization of data items. It represents
the kind of value that tells what operations can be performed on a particular
data.

Following are the standard or built-in data type of Python:

 Numeric

 Sequence Type

 Boolean

 Set

 Dictionary
Numbers
Number stores numeric values. The integer, float, and complex values belong to a
Python Numbers data-type.

Python supports three types of numeric data.

1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc.
Python has no restriction on the length of an integer. Its value belongs to int
2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It
is accurate upto 15 decimal points.
3. complex - A complex number contains an ordered pair, i.e., x + iy where x and
y denote the real and imaginary parts, respectively. The complex numbers like
2.14j, 2.0 + 2.3j, etc.

Sequence Type
String

The string can be defined as the sequence of characters represented in the quotation
marks. In Python, we can use single, double, or triple quotes to define a string.

x = "Hello World"

#display x:
print(x)

#display the data type of x:


print(type(x))

List

Python Lists are similar to arrays in C. However, the list can contain data of different
types. The items stored in the list are separated with a comma (,) and enclosed within
square brackets [].

list1 = [1, "hi", "Python", 2]

#Printing the list1


print (list1)
Tuple
A tuple is similar to the list in many ways. Like lists, tuples also contain the collection
of the items of different data types. The items of the tuple are separated with a
comma (,) and enclosed in parentheses ().

tup = ("hi", "Python", 2)


# Checking type of tup
print (type(tup))

#Printing the tuple


print (tup)

Dictionary
Dictionary is an unordered set of a key-value pair of items.

The items in the dictionary are separated with the comma (,) and
enclosed in the curly braces {}.

Consider the following example.

d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}

# Printing dictionary

print (d)

Boolean
Boolean type provides two built-in values, True and False. These values are used to
determine the given statement true or false. It denotes by the class bool. True can be
represented by any non-zero value or 'T' whereas false can be represented by the 0
or 'F'. Consider the following example.

# Python program to check the boolean type


print(type(True))
print(type(False))
Set
Python Set is the unordered collection of the data type. It is iterable, mutable(can
modify after creation), and has unique elements. In set, the order of the elements is
undefined; it may return the changed sequence of the element. The set is created by
using a built-in function set(), or a sequence of elements is passed in the curly
braces and separated by the comma. It can contain various types of values. Consider
the following example.

# Creating Empty set


set1 = set()

set2 = {'James', 2, 3,'Python'}

#Printing Set value


print(set2)

Python Operators
The operator can be defined as a symbol which is responsible for a particular
operation between two operands. Operators are the pillars of a program on which
the logic is built in a specific programming language. Python provides a variety of
operators, which are described as follows.

o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators

Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations between two
operands. It includes + (addition), - (subtraction), *(multiplication), /(divide),
%(reminder), //(floor division), and exponent (**) operators.

Consider the following table for a detailed explanation of arithmetic operators.


Operator Description

+ (Addition) It is used to add two operands. For example, if a = 20, b = 10 => a+b = 30

- (Subtraction) It is used to subtract the second operand from the first operand. If the first operand is l
than the second operand, the value results negative. For example, if a = 20, b = 10 => a
= 10

/ (divide) It returns the quotient after dividing the first operand by the second operand. For examp
if a = 20, b = 10 => a/b = 2.0

* It is used to multiply one operand with the other. For example, if a = 20, b = 10 => a * b
(Multiplication) 200

% (reminder) It returns the reminder after dividing the first operand by the second operand. For examp
if a = 20, b = 10 => a%b = 0

** (Exponent) It is an exponent operator represented as it calculates the first operand power to


second operand.

// (Floor It gives the floor value of the quotient produced by dividing the two operands.
division)

Comparison operator
Comparison operators are used to comparing the value of the two operands and
returns Boolean true or false accordingly. The comparison operators are described in
the following table.

Operator Description

== If the value of two operands is equal, then the condition becomes true.

!= If the value of two operands is not equal, then the condition becomes true.
<= If the first operand is less than or equal to the second operand, then the condition becomes tru

>= If the first operand is greater than or equal to the second operand, then the condition becom
true.

> If the first operand is greater than the second operand, then the condition becomes true.

< If the first operand is less than the second operand, then the condition becomes true.

Assignment Operators
The assignment operators are used to assign the value of the right expression to the
left operand. The assignment operators are described in the following table.

Operator Description

= It assigns the value of the right expression to the left operand.

+= It increases the value of the left operand by the value of the right operand and assigns
modified value back to left operand. For example, if a = 10, b = 20 => a+ = b will be equal to
a+ b and therefore, a = 30.

-= It decreases the value of the left operand by the value of the right operand and assigns
modified value back to left operand. For example, if a = 20, b = 10 => a- = b will be equal to
a- b and therefore, a = 10.

*= It multiplies the value of the left operand by the value of the right operand and assigns
modified value back to then the left operand. For example, if a = 10, b = 20 => a* = b will
equal to a = a* b and therefore, a = 200.

%= It divides the value of the left operand by the value of the right operand and assigns the remin
back to the left operand. For example, if a = 20, b = 10 => a % = b will be equal to a = a % b a
therefore, a = 0.

**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign 4**2 = 16 to a.
//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign 4//3 = 1 to a.

Bitwise Operators
The bitwise operators perform bit by bit operation on the values of the two
operands. Consider the following example.

Operator Description

& (binary If both the bits at the same place in two operands are 1, then 1 is copied to the res
and) Otherwise, 0 is copied.

| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the resulting bit will be 1.

^ (binary xor) The resulting bit will be 1 if both the bits are different; otherwise, the resulting bit will be 0.

~ (negation) It calculates the negation of each bit of the operand, i.e., if the bit is 0, the resulting bit will b
and vice versa.

<< (left shift) The left operand value is moved left by the number of bits present in the right operand.

>> (right The left operand is moved right by the number of bits present in the right operand.
shift)

Logical Operators
The logical operators are used primarily in the expression evaluation to make a
decision. Python supports the following logical operators.

Operator Description

and If both the expression are true, then the condition will be true. If a and b are the two expressio
a → true, b → true => a and b → true.
or If one of the expressions is true, then the condition will be true. If a and b are the two expressio
a → true, b → false => a or b → true.

not If an expression a is true, then not (a) will be false and vice versa.

Membership Operators
Python membership operators are used to check the membership of value inside a
Python data structure. If the value is present in the data structure, then the resulting
value is true otherwise it returns false.

Operator Description

in It is evaluated to be true if the first operand is found in the second operand (list, tuple,
dictionary).

not in It is evaluated to be true if the first operand is not found in the second operand (list, tuple,
dictionary).

Identity Operators
The identity operators are used to decide whether an element certain class or type.

Operator Description

is It is evaluated to be true if the reference present at both sides point to the same object.

is not It is evaluated to be true if the reference present at both sides do not point to the same object
Python - Conditional Statements or Decision Making
Decision making is anticipation of conditions occurring while execution of the program and
specifying actions taken according to the conditions.

Python If-else statements


Decision making is the most important aspect of almost all the programming languages. As
the name implies, decision making allows us to run a particular block of code for a particular
decision.

In python, decision making is performed by the following statements.

Statement Description

If Statement The if statement is used to test a specific condition. If the condition is true, a block
code (if-block) will be executed.

If - else The if-else statement is similar to if statement except the fact that, it also provides t
Statement block of the code for the false case of the condition to be checked. If the conditi
provided in the if statement is false, then the else statement will be executed.

Nested if Nested if statements enable us to use if ? else statement inside an outer if s


Statement

The if statement
The if statement is used to test a particular condition and if the condition is true, it
executes a block of code known as if-block. The condition of if statement can be any
valid logical expression which can be either evaluated to true or false.

Difference between JDK, JRE, and JVM


The syntax of the if-statement is given below.

if expression:
statement

Example 1
num = int(input("enter the number?"))
if num%2 == 0:
print("Number is even")

The if-else statement


The if-else statement provides an else block combined with the if statement which is
executed in the false case of the condition.

If the condition is true, then the if-block is executed. Otherwise, the else-block is
executed.

The syntax of the if-else statement is given below.

if condition:
#block of statements
else:
#another block of statements (else-block)
Example : Program to check whether a number is even or not.
num = int(input("enter the number?"))
if num%2 == 0:
print("Number is even...")
else:
print("Number is odd...")

The elif statement


The elif statement enables us to check multiple conditions and execute the specific
block of statements depending upon the true condition among them. We can have
any number of elif statements in our program depending upon our need. However,
using elif is optional.

The elif statement works like an if-else-if ladder statement in C. It must be succeeded
by an if statement.

The syntax of the elif statement is given below.

if expression 1:
# block of statements

elif expression 2:
# block of statements

elif expression 3:
# block of statements

else:
# block of statements

Example
number = int(input("Enter the number?"))
if number==10:
print("number is equals to 10")
elif number==50:
print("number is equal to 50");
elif number==100:
print("number is equal to 100");
else:
print("number is not equal to 10, 50 or 100");
Python Loops
The flow of the programs written in any programming language is sequential by
default. Sometimes we may need to alter the flow of the program. The execution of a
specific code may need to be repeated several numbers of times.

For this purpose, The programming languages provide various types of loops which
are capable of repeating some specific code several numbers of times. Consider the
following diagram to understand the working of a loop statement.

There are the following loop statements in Python.

Loop Description
Statement

for loop The for loop is used in the case where we need to execute some part of the code un
the given condition is satisfied. The for loop is also called as a per-tested loop. It
better to use for loop if the number of iteration is known in advance.

while loop The while loop is to be used in the scenario where we don't know the number
iterations in advance. The block of statements is executed in the while loop until t
condition specified in the while loop is satisfied. It is also called a pre-tested loop.

Python for loop


The for loop in Python is used to iterate the statements or a part of the program
several times. It is frequently used to traverse the data structures like list, tuple, or
dictionary.
The syntax of for loop in python is given below.

for iterating_var in sequence:


statement(s)

The for loop flowchart

Example- 1: Program to print the table of the given number .

list = [1,2,3,4,5,6,7,8,9,10]

n=5

for i in list:

c = n*i

print(c)

For loop Using range() function


The range() function
The range() function is used to generate the sequence of the numbers. If we pass
the range(10), it will generate the numbers from 0 to 9. The syntax of the range()
function is given below.

Syntax:

range(start,stop,step size)

Example:

for i in range(10):

print(i)

Nested for loop in python


Python allows us to nest any number of for loops inside a for loop. The inner loop is
executed n number of times for every iteration of the outer loop. The syntax is given
below.

Syntax

for iterating_var in sequence:


for iterating_var in sequence:
statements(s)
statements(s)

Example

adj = ["red", "big", "tasty"]


fruits = ["apple", "banana", "cherry"]

for x in adj:
for y in fruits:
print(x, y)

Else in For Loop


The else keyword in a for loop specifies a block of code to be executed when
the loop is finished:

Example
for x in range(6):
print(x)
else:
print("Finally finished!")

Python While loop


The Python while loop allows a part of the code to be executed until the given
condition returns false. It is also known as a pre-tested loop.

The syntax is given below.

while expression:

statements

While loop Flowchart

Example-1: Program to print 1 to 10 using while loop


i=1
#The while loop will iterate until condition becomes false.
While(i<=10):
print(i)
i=i+1
The syntax for a nested while loop statement in Python programming language is
as follows −
while expression:
while expression:
statement(s)
statement(s)

Example
The following program uses a nested for loop to find the prime numbers from 2 to
100 −
Live Demo

#!/usr/bin/python

i = 2
while(i < 100):
j = 2
while(j <= (i/j)):
if not(i%j): break
j = j + 1
if (j > i/j) : print i, " is prime"
i = i + 1

print "Good bye!"

Loop Control Statements


Python offers the following control statement to use within the while loop.

1. Continue Statement - When the continue statement is encountered, the control


transfer to the beginning of the loop.

The continue statement can be used in both while and for loops.

Syntax
continue

Flow Diagram
Let's understand the following example.

Continue to the next iteration if i is 3:

i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)

2. Break Statement - When the break statement is encountered, it brings control


out of the loop.
With the break statement we can stop the loop even if the while condition is
true:
The break statement can be used in both while and for loops.

Syntax
The syntax for a break statement in Python is as follows −
break

Example
Exit the loop when i is 3:

i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1

3. Pass Statement - The pass statement is used to declare the empty loop.
The pass statement is a null operation; nothing happens when it executes. It is also
used to define empty class, function, and control statement. Let's understand the
following example.

Syntax
pass

Example for letter in 'Python':

for letter in 'Python':


if letter == 'h':
pass
print ('This is pass block')
print ('Current Letter :', letter)

You might also like