Python Unit1
Python Unit1
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 [Link]. 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."
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.
NAMING OF VARIABLES
• Variable names can contain uppercase and lowercase letters, digits (But they cannot start with
a digit), and the special character _.
• Python variable Names are case-sensitive e.g., Julie and julie are different names.
• There are a small number of reserved words (sometimes called keywords) in Python that
have built-in meanings and cannot be used as variable names.
DECLARING VARIABLE AND ASSIGNING VALUES
Python does not bound us to declare variable before using in the application. It allows us to create
variable at required time. We don't need to declare explicitly variable in Python. When we assign any
value to the variable that variable is declared automatically. The equal (=) operator is used to assign
value to a variable.
Eg:
MULTIPLE ASSIGNMENT
Python allows us to assign a value to multiple variables in a single statement which is also known as
multiple assignment. We can apply multiple assignments in two ways either by assigning a single value
to multiple variables or assigning multiple values to multiple variables. Lets see given examples.
1. Assigning single value to multiple variables
Eg:
x=y=z=50
print x
print y
print z
Output:
>>>
50
50
50
>>>
[Link] multiple values to multiple variables:
Eg:
a,b,c=5,10,15
print a
print b
print c
Output:
>>>
5
10
15
The values will be assigned in the order in which variables appears.
RESERVED WORDS
• Some of the reserved words in python are: and, as, assert, break, class, continue, def, del, elif,
else, except, exec, finally, for, from, global, if, import, in, is, lambda, not, or, pass, print, raise,
return, try, with, while, and yield.
OPERATIONS ON OBJECTS
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 particular programming language. Python provides a variety of operators described
as follows.
o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical 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
(**).
Consider the following table for a detailed explanation of arithmetic operators
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.
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 less than the second operand, the value result negative. For
example, if a = 20, b = 10 => a ? b = 10
/ (divide) It returns the quotient after dividing the first operand by the second operand.
For example, if a = 20, b = 10 => a/b = 2
* It is used to multiply one operand with the other. For example, if a = 20, b =
(Multiplication) 10 => a * b = 200
% (reminder) It returns the reminder after dividing the first operand by the second
operand. For example, if a = 20, b = 10 => a%b = 0
// (Floor It gives the floor value of the quotient produced by dividing the two operands.
division)
PYTHON 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
<> If the value of two operands is not equal, then the condition
becomes 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.
Operator Description
= It assigns the 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 assign the modified value back to left operand. For
example, if a = 10, b = 20 => a+ = b will be equal to a = a+ b and
therefore, a = 30.
-= It decreases the value of the left operand by the value of the right
operand and assign the modified value back to left operand. For
example, if a = 20, b = 10 => a- = b will be equal to a = a- b and
therefore, a = 10.
*= It multiplies the value of the left operand by the value of the right
operand and assign the modified value back to left operand. For
example, if a = 10, b = 20 => a* = b will be 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 assign the reminder back to left operand. For example, if a = 20, b
= 10 => a % = b will be equal to a = a % b and 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.
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 expressions, 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 expressions, a → true, b → false => a or b → true.
not If an expression a is true then not (a) will be false and vice versa.
PYTHON COMMENTS
Comments in Python can be used to explain any program code. It can also be used to hide the code
as well. Comments are the most helpful stuff of any program. It enables us to understand the way, a
program works. In python, any statement written along with # symbol is known as a comment. The
interpreter does not interpret the comment. Comment is not a part of the program, but it enhances
the interactivity of the program and makes the program readable.
Python supports two types of comments:
1. Single Line Comment:
In case user wants to specify a single line comment, then comment must start with #
Eg:
# This is single line comment.
print "Hello Python"
Output:
Hello Python
2. Multi Line Comment:
Multi lined comment can be given inside triple quotes.
eg:
''''' This
Is
Multipline comment'''
eg:
#single line comment
print "Hello Python"
'''''This is
multiline comment'''
BRANCHING PROGRAMS
Two types of computations in python are:
1. Straight line programs
They execute one statement after another in the order in which they appear, and stop
when they run out of statements. The kinds of computations we can describe with
straight-line programs
2. Branching programs
Branching statements are conditional. A conditional statement has three parts
– A test
– Block of code to be executed if test is true
– Optional block of code if test is false
2. If - else Statement - The if-else statement is similar to if statement except the fact that, it also
provides the block of the code for the false case of the condition to be checked. If the condition
provided in the if statement is false, then the else statement will be executed.
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 [Link] 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 1
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");
Advantages of loops
There are the following advantages of loops in Python.
1. It provides code re-usability.
2. Using loops, we do not need to write the same code again and again.
3. Using loops, we can traverse over the elements of data structures (array or linked lists).
In the above example, for loop is executed completely since there is no break statement in the loop.
The control comes out of the loop and hence the else block is executed.
Ex:
for i in range(0,5):
print(i)
break;
else:
print("for loop is exhausted");
print("The loop is broken due to break statement...came out of loop")
In the above example, the loop is broken due to break statement therefore the else statement will
not be executed. The statement present immediate next to else block will be executed.
Ex:
i=1;
while i<=10:
print(i);
i=i+1;
1. slicing - the slice operator [] is used to access the individual characters of the string. However,
we can use the : (colon) operator in python to access the substring. Consider the following
example
Here, we must notice that the upper range given in the slice operator is always exclusive i.e., if str =
'python' is given, then str[1:3] will always include str[1] = 'p', str[2] = 'y', str[3] = 't' and nothing else.
Reassigning strings
Updating the content of the strings is as easy as assigning it to a new string. The string object doesn't
support item assignment i.e., A string can only be replaced with a new string since its content can not
be partially replaced. Strings are immutable in python.
Consider the following example.
Example 1
str = "HELLO"
str[0] = "h"
print(str)
2. len() function is an inbuilt function in Python programming language that returns the
length of the string.
Syntax:
len(string)
Ex:
string = "geeks"
print(len(string))
output =5
Ex:
# Length of below string is 15
string = "geeks for geeks"
print(len(string))
INPUT
Values can be accepted from the user using input() function
E.g1:
name=input(“Enter the name”)
print(“you entered“, name)
E.g 2:
a = float(input('Enter a: '))
b = float(input('Enter b: '))
print('The values are {0} and {1}'.format(a, b))
FUNCTIONS
• We can define functions to provide the required functionality. Here are simple rules to
define a function in Python.
• Function blocks begin with the keyword def followed by the function name and parentheses
( ( ) ).
• Any input parameters or arguments should be placed within these parentheses.
• The first statement of a function can be an optional statement - the documentation string of
the function or docstring.
• The code block within every function starts with a colon (:) and is indented.
• The statement return [expression] exits a function, optionally passing back an expression to
the caller. A return statement with no arguments is the same as return None.
• Syntax
def functionname( parameters ):
"function_docstring"
return [expression]
In python, a function must be defined before the function calling otherwise the python interpreter
gives an error. Once the function is defined, we can call it from another function or the python prompt.
To call the function, use the function name followed by the parentheses.
A simple function that prints the message "Hello Word" is given below.
def hello_world():
print("hello world")
hello_world()
PYTHON PASS
In Python, pass keyword is used to execute nothing; it means, when we don't want to execute code,
the pass can be used to execute empty. It is same as the name refers to. It just makes the control to
pass by without executing any code. If we want to bypass any code pass statement can be used.
Python Pass Syntax
pass
x=3
y =2
z = f(x)
print('z =', z)
print('x =', x)
print('y =', y)
SPECIFICATIONS
• Specifications: Standards maintained by developer
• Assumptions: Conditions that must be met by the client
• Guarantees: Conditions that must be met by the functions
• Decomposition: Ability to break down the program into sub parts for better understanding
• Abstraction: Hiding non essential details
RECURSION
• When a function call itself is knows as recursion
• A base condition is must in every recursive programs otherwise it will continue to execute
forever like an infinite loop.
• A recursive program needs to have a termination condition
Ex:
def fact(n):
if n == 0:
return 1
else:
return n * fact(n - 1)
print(fact(0))
print(fact(5))
GLOBAL VARIABLES
• Global variables are the one that are defined and declared outside a function and we need
to use them inside a function.
• # This function uses global variable s
def f():
print s
# Global scope
s = “Python is easier to learn"
f()
MODULES
• Allows user to logically organize Python code.
• Grouping related code into a module makes the code easier to understand and use.
• A module is a Python object with arbitrarily named attributes that user can bind and
reference.
• Simply, a module is a file consisting of Python code.
• A module can define functions, classes and variables. A module can also include runnable
code.
FILE
• What is a file?
– File is a named location on disk to store related information. It is used to
permanently store data in a non-volatile memory (e.g. hard disk).
• A file operation takes place in the following order.
– Open a file
– Read or write (perform operation)
– Close the file
• Open a file
• Python has a built-in function open() to open a file. This function returns a file object, also
called a handle, as it is used to read or modify the file accordingly.
• f = open("[Link]",'w') # write in text mode
File Operations
• Syntax
• file object = open(file_name [, access_mode][, buffering]) Here are parameter details −
– file_name − Name of the file to be opened
– access_mode − The access_mode determines the mode in which the file has to be
opened, i.e., read, write, append, etc. This is optional parameter and the default file
access mode is read (r).
– buffering − If the buffering value is set to 0, no buffering takes place. If the buffering
value is 1, line buffering is performed while accessing a file. If you specify the buffering
value as an integer greater than 1, then buffering action is performed with the
indicated buffer size. If negative, the buffer size is the system default(default
behavior).
Access Modes
• r-
Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the
default mode.
• rb
Opens a file for reading only in binary format. The file pointer is placed at the beginning of
the file. This is the default mode.
• r+
Opens a file for both reading and writing. The file pointer placed at the beginning of the file.
• rb+
Opens a file for both reading and writing in binary format. The file pointer placed at the
beginning of the file.
• wb+
Opens a file for both writing and reading in binary format. Overwrites the existing file if the
file exists. If the file does not exist, creates a new file for reading and writing.
• a
Opens a file for appending. The file pointer is at the end of the file if the file exists. That is,
the file is in the append mode. If the file does not exist, it creates a new file for writing.
• ab
Opens a file for appending in binary format. The file pointer is at the end of the file if the file
exists. That is, the file is in the append mode. If the file does not exist, it creates a new file
for writing.
• w
• Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist,
creates a new file for writing.
• wb
Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file
does not exist, creates a new file for writing.
• w+
Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the
file does not exist, creates a new file for reading and writing.
• a+
Opens a file for both appending and reading. The file pointer is at the end of the file if the
file exists. The file opens in the append mode. If the file does not exist, it creates a new file
for reading and writing.
• ab+
Opens a file for both appending and reading in binary format. The file pointer is at the end of
the file if the file exists. The file opens in the append mode. If the file does not exist, it
creates a new file for reading and writing.
Ex:
#a file named "test1", will be opened with the reading mode.
#closing a file
[Link]()