Python Introduction Lecture 1
Python Introduction Lecture 1
language.
Python is an interpreted scripting language also. Guido Van Rossum is known as the founder of
python programming.
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's syntax and dynamic typing with its interpreted nature, makes it an ideal language for
scripting and rapid application development.
Python supports multiple programming pattern, including object oriented, imperative and
functional or procedural programming styles.
Python is not intended to work on special area such as web programming. That is why it is
known as multipurpose because it can be used with web, enterprise, 3D CAD etc.
We don't need to use data types to declare variable because it is dynamically typed so we can
write a=10 to assign an integer value in an integer variable.
Python makes the development and debugging fast because there is no compilation step included
in python development and edit-test-debug cycle is very fast.
Python Features
Python is easy to learn and use. It is developer-friendly and high level programming language.
2) Expressive Language
Python language is more expressive means that it is more understandable and readable.
3) Interpreted Language
Python is an interpreted language i.e. interpreter executes the code line by line at a time. This
makes debugging easy and thus suitable for beginners.
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.
Python language is freely available at offical web address.The source-code is also available.
Therefore it is open source.
6) Object-Oriented Language
Python supports object oriented language and concepts of classes and objects come into
existence.
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.
Python has a large and broad library and prvides rich set of module and functions for rapid
application development.
Python Applications
Python is known for its general purpose nature that makes it applicable in almost each domain of
software development. Python as a whole can be used in any sphere of development.
1) Web Applications
We can use Python to develop web applications. It provides libraries to handle internet protocols
such as HTML and XML, JSON, Email processing, request, beautifulSoup, Feedparser etc. It
also provides Frameworks such as Django, Pyramid, Flask etc to design and delelop web based
applications. Some important developments are: PythonWikiEngines, Pocoo,
PythonBlogSoftware etc.
Python provides Tk GUI library to develop user interface in python based application. Some
other useful toolkits wxWidgets, Kivy, pyqt that are useable on several platforms. The Kivy is
popular for writing multitouch applications.
3) Software Development
Python is helpful for software development process. It works as a support language and can be
used for build control and management, testing etc.
Python is popular and widely used in scientific and numeric computing. Some useful library and
package are SciPy, Pandas, IPython etc. SciPy is group of packages of engineering, science and
mathematics.
5) Business Applications
Python is used to build Bussiness applications like ERP and e-commerce systems. Tryton is a
high level application platform.
6) Console Based Application
We can use Python to develop console based applications. For example: IPython.
Python is awesome to perform multiple tasks and can be used to develop multimedia
applications. Some of real applications are: TimPlayer, cplay etc.
8) 3D CAD Applications
To create CAD application. Fandango is a real application which provides full features of CAD.
9) Enterprise Applications
Python can be used to create applications which can be used within an Enterprise or an
Organization. Some real time applications are: OpenErp, Tryton, Picalo etc.
Using Python several application can be developed for image. Applications developed are:
VPython, Gogh, imgSeek etc.
There are several such applications which can be developed using Python
Installation on Windows
Python provides us the feature to execute the python statement one by one at the interactive
prompt. It is preferable in the case where we are concerned about the output of each line of
our python program.
o To open the interactive mode, open the terminal (or command prompt) and type python
Interpreter prompt is good to run the individual statements of the code. However, we can not
write the code every-time on the terminal.
We need to write our code into a file which can be executed later. For this purpose, open an
editor like notepad, create a file named first.py (python used .py extension) and write the
following code in it.
Print ("hello world"); #here, we have used print() function to print the message on the console.
To run this file named as first.py, we need to run the following command on the terminal.
On Windows, we have an alternative like notepad or notepad++ to edit the code. However, these
editors are not used as IDE for python since they are unable to show the syntax related
suggestions.
JetBrains provides the most popular and a widely used cross-platform IDE PyCharm to run the
python programs.
Anaconda Distribution
Python Variables
Variable is a name which is used to refer memory location. Variable also known as identifier and
used to hold value.
In Python, we don't need to specify the type of variable because Python is a type infer language
and smart enough to get variable type.
Variable names can be a group of both letters and digits, but they have to begin with a letter or
an underscore.
It is recomended to use lowercase letters for variable name. Rahul and rahul both are two
different variables.
Identifier Naming
Variables are the example of identifiers. An Identifier is used to identify the literals used in the
program. The rules to name an identifier are given below.
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.
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.
Eg:
1. x=y=z=50
2. print x
3. print y
4. print z
Output:
1. >>>
2. 50
3. 50
4. 50
5. >>>
Eg:
1. a,b,c=5,10,15
2. print a
3. print b
4. print c
Output:
1. >>>
2. 5
3. 10
4. 15
5. >>>
ii) Comments
a)Tokens:
o Tokens can be defined as a punctuator mark, reserved words and each individual word in
a statement.
o Token is the smallest unit inside the given program.
o Keywords.
o Identifiers.
o Literals.
o Operators.
Tuples:
o Tuple is another form of collection where different type of data can be stored.
o It is similar to list where data is separated by commas. Only the difference is that list uses
square bracket and tuple uses parenthesis.
o Tuples are enclosed in parenthesis and cannot be changed.
Eg:
1. >>> tuple=('rahul',100,60.4,'deepak')
2. >>> tuple1=('sanjay',10)
3. >>> tuple
4. ('rahul', 100, 60.4, 'deepak')
5. >>> tuple[2:]
6. (60.4, 'deepak')
7. >>> tuple1[0]
8. 'sanjay'
9. >>> tuple+tuple1
10. ('rahul', 100, 60.4, 'deepak', 'sanjay', 10)
11. >>>
Dictionary:
o Dictionary is a collection which works on a key-value pair.
o It works like an associated array where no two keys can be same.
o Dictionaries are enclosed by curly braces ({}) and values can be retrieved by square
bracket ([]).
Eg:
1. >>> dictionary={'name':'charlie','id':100,'dept':'it'}
2. >>> dictionary
3. {'dept': 'it', 'name': 'charlie', 'id': 100}
4. >>> dictionary.keys()
5. ['dept', 'name', 'id']
6. >>> dictionary.values()
7. ['it', 'charlie', 100]
8. >>>
Variables can hold values of different data types. Python is a dynamically typed language hence
we need not define the type of the variable while declaring it. The interpreter implicitly binds the
value with its type.
Python enables us to check the type of the variable used in the program. Python provides us
the type() function which returns the type of the variable passed.
Consider the following example to define the values of different data types and checking its type.
1. A=10
2. b="Hi Python"
3. c = 10.5
4. print(type(a));
5. print(type(b));
6. print(type(c));
Output:
<type 'int'>
<type 'str'>
<type 'float'>
A variable can hold different types of values. For example, a person?s name must be stored as a
string whereas its id must be stored as an integer.
Python provides various standard data types that define the storage method on each of them. The
data types defined in Python are given below.
1. Numbers
2. String
3. List
4. Tuple
5. Dictionary
Numbers
Number stores numeric values. Python creates Number objects when a number is assigned to a
variable. For example;
Python allows us to use a lower-case L to be used with long integers. However, we must always
use an upper-case L to avoid confusion.
A complex number contains an ordered pair, i.e., x + iy where x and y denote the real and
imaginary parts respectively).
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.
String handling in python is a straightforward task since there are various inbuilt functions and
operators provided.
In the case of string handling, the operator + is used to concatenate two strings as the
operation "hello"+" python" returns "hello python".
The operator * is known as repetition operator as the operation "Python " *2 returns "Python
Python ".
List
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 [].
We can use slice [:] operators to access the data of the list. The concatenation operator (+) and
repetition operator (*) works with the list in the same way as they were working with the strings.
Output:
[2]
[1, 'hi']
[1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2]
[1, 'hi', 'python', 2, 1, 'hi', 'python', 2, 1, 'hi', 'python', 2]
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 ().
A tuple is a read-only data structure as we can't modify the size and value of the items of a tuple.
1. t = ("hi", "python", 2)
2. print (t[1:]);
3. print (t[0:1]);
4. print (t);
5. print (t + t);
6. print (t * 3);
7. print (type(t))
8. t[2] = "hi";
Output:
('python', 2)
('hi',)
('hi', 'python', 2)
('hi', 'python', 2, 'hi', 'python', 2)
('hi', 'python', 2, 'hi', 'python', 2, 'hi', 'python', 2)
<type 'tuple'>
Traceback (most recent call last):
File "main.py", line 8, in <module>
t[2] = "hi";
TypeError: 'tuple' object does not support item assignment
Dictionary
Dictionary is an ordered set of a key-value pair of items. It is like an associative array or a hash
table where each key stores a specific value. Key can hold any primitive data type whereas value
is an arbitrary Python object.
The items in the dictionary are separated with the comma and enclosed in the curly braces {}.
Output:
Python Literals
I. String literals:
String literals can be formed by enclosing a text in the quotes. We can use both single as well as
double quotes for a String.
Eg:
"Aman" , '12345'
Types of Strings:
a).Single line String- Strings that are terminated within a single line are known as Single line
Strings.
Eg:
1. >>> text1='hello'
b).Multi line String- A piece of text that is spread along multiple lines is known as Multiple line
String.
Eg:
1. >>> text1='hello\
2. user'
3. >>> text1
4. 'hellouser'
5. >>>
Eg:
1. >>> str2='''welcome
2. to
3. SSSIT'''
4. >>> print str2
5. welcome
6. to
7. SSSIT
8. >>>
A Boolean literal can have any of the two values: True or False.
IV. Special literals.
None is used to specify to that field that is not created. It is also used for end of lists in Python.
Eg:
1. >>> val1=10
2. >>> val2=None
3. >>> val1
4. 10
5. >>> val2
6. >>> print val2
7. None
8. >>>
V.Literal Collections.
List:
o List contain items of different data types. Lists are mutable i.e., modifiable.
o The values stored in List are separated by commas(,) and enclosed within a square
brackets([]). We can store different type of data in a List.
o Value stored in a List can be retrieved using the slice operator([] and [:]).
o The plus sign (+) is the list concatenation and asterisk(*) is the repetition operator.
Eg:
1. >>> list=['aman',678,20.4,'saurav']
2. >>> list1=[456,'rahul']
3. >>> list
4. ['aman', 678, 20.4, 'saurav']
5. >>> list[1:3]
6. [678, 20.4]
7. >>> list+list1
8. ['aman', 678, 20.4, 'saurav', 456, 'rahul']
9. >>> list1*2
10. [456, 'rahul', 456, 'rahul']
11. >>>
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 particular
programming language. Python provides a variety of operators 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 (**).
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 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 = 10 =>
(Multiplication) 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)
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.
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 true.
>= If the first operand is greater than or equal to the second operand, then the condition
becomes true.
<> 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.
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 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.
//= 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.
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.
Membership Operators
Python membership operators are used to check the membership of value inside a 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, or dictionary).
not in It is evaluated to be true if the first operand is not found in the second operand (list, tuple, or
dictionary).
Identity Operators
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 side do not point to the same object.
Operator Precedence
The precedence of the operators is important to find out since it enables us to know which
operator should be evaluated first. The precedence table of the operators in python is given
below.
Operator Description
** The exponent operator is given priority over all the others used in the
expression.
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.
In case user wants to specify a single line comment, then comment must start with ?#?
Eg:
Hello Python
eg:
1. ''''' This
2. Is
3. Multipline comment'''
eg:
Output:
Hello Python
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. Here, the decisions are made on the validity of the particular conditions. Condition
checking is the backbone of decision making.
If Statement The if statement is used to test a specific condition. If the condition is true, a block of
code (if-block) will be executed.
If - else The if-else statement is similar to if statement except the fact that, it also provides the
Statement 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.
Nested if Nested if statements enable us to use if ? else statement inside an outer if statement.
Statement
Indentation in Python
For the ease of programming and to achieve simplicity, python doesn't allow the use of
parentheses for the block level code. In Python, indentation is used to declare a block. If two
statements are at the same indentation level, then they are the part of the same block.
Generally, four spaces are given to indent the statements which are a typical amount of
indentation in python.
Indentation is the most used part of the python language since it declares the block of code. All
the statements of one block are intended at the same level indentation. We will see how the
actual indentation takes place in decision making and other stuff in python.
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.
1. if expression:
2. statement
Example 1
1. num = int(input("enter the number?"))
2. if num%2 == 0:
3. print("Number is even")
Output:
Output:
Enter a? 100
Enter b? 120
Enter c? 130
c is largest
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.
1. if condition:
2. #block of statements
3. else:
4. #another block of statements (else-block)
Output:
Output:
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.
1. if expression 1:
2. # block of statements
3.
4. elif expression 2:
5. # block of statements
6.
7. elif expression 3:
8. # block of statements
9.
10. else:
11. # block of statements
Example 1
1. number = int(input("Enter the number?"))
2. if number==10:
3. print("number is equals to 10")
4. elif number==50:
5. print("number is equal to 50");
6. elif number==100:
7. print("number is equal to 100");
8. else:
9. print("number is not equal to 10, 50 or 100");
Output:
Example 2
marks = int(input("Enter the marks? "))
if marks > 85 and marks <= 100:
print("Congrats ! you scored grade A ...")
elif marks > 60 and marks <= 85:
print("You scored grade B + ...")
elif marks > 40 and marks <= 60:
print("You scored grade B ...")
elif (marks > 30 and marks <= 40):
print("You scored grade C ...")
else:
print("Sorry you are fail ?")
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.
Why we use loops in python?
The looping simplifies the complex problems into the easy ones. It enables us to alter the flow of
the program so that instead of writing the same code again and again, we can repeat the same
code for a finite number of times. For example, if we need to print the first 10 natural numbers
then, instead of using the print statement 10 times, we can print inside a loop which runs up to 10
iterations.
Advantages of loops
for loop The for loop is used in the case where we need to execute some part of the code
until the given condition is satisfied. The for loop is also called as a per-tested loop.
It is 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 of
iterations in advance. The block of statements is executed in the while loop until
the condition specified in the while loop is satisfied. It is also called a pre-tested
loop.
do-while The do-while loop continues until a given condition satisfies. It is also called post
loop tested loop. It is used when it is necessary to execute the loop at least once (mostly
menu driven programs).
The print() function inserts a new line at the end, by default. In Python 2, it can be suppressed
by putting ',' at the end. In Python 3, "end =' '" appends space instead of newline.
The print() function inserts a new line at the end, by default In Python 3, "end =' '" appends
space instead of newline.
Output:
0123456789
Python for loop example : printing the table of the given number
1. i=1;
2. num = int(input("Enter a number:"));
3. for i in range(1,11):
4. print("%d X %d = %d"%(num,i,num*i));
Output:
Enter a number:10
10 X 1 = 10
10 X 2 = 20
10 X 3 = 30
10 X 4 = 40
10 X 5 = 50
10 X 6 = 60
10 X 7 = 70
10 X 8 = 80
10 X 9 = 90
10 X 10 = 100
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 of the nested for loop in python
is given below.
Output:
# iterating by row of A
for i in range(len(A)):
# iterating by coloum by B
for j in range(len(B[0])):
# iterating by rows of B
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]
for r in result:
print(r)
Output:
[114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]
Unlike other languages like C, C++, or Java, python allows us to use the else statement with the
for loop which can be executed only when all the iterations are exhausted. Here, we must notice
that if the loop contains any of the break statement then the else statement will not be executed.
Example 1
1. for i in range(0,5):
2. print(i)
3. else:print("for loop completely exhausted, since there is no break.");
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.
Output:
0
1
2
3
4
Example 2
1. for i in range(0,5):
2. print(i)
3. break;
4. else:print("for loop is exhausted");
5. 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.
Output:
It can be viewed as a repeating if statement. The while loop is mostly used in the case
where the number of iterations is not known in advance.
1. while expression:
2. statements
Here, the statements can be a single statement or the group of statements. The expression
should be any valid python expression resulting into true or false. The true is any non-zero
value.
Example 1
1. i=1;
2. while i<=10:
3. print(i);
4. i=i+1;
Output:
1
2
3
4
5
6
7
8
9
10
Example 2
i=1
number=0
b=9
number = int(input("Enter the number?"))
while i<=10:
print("%d X %d = %d \n"%(number,i,number*i));
i = i+1;
Output:
10 X 1 = 10
10 X 2 = 20
10 X 3 = 30
10 X 4 = 40
10 X 5 = 50
10 X 6 = 60
10 X 7 = 70
10 X 8 = 80
10 X 9 = 90
10 X 10 = 100
Any non-zero value in the while loop indicates an always-true condition whereas 0 indicates
the always-false condition. This type of approach is useful if we want our program to run
continuously in the loop without any disturbance.
Example 1
1. while (1):
2. print("Hi! we are inside the infinite while loop");
Output:
Example 2
1. var = 1
2. while var != 2:
3. i = int(input("Enter the number?"))
4. print ("Entered value is %d"%(i))
Output:
1. i=1;
2. while i<=5:
3. print(i)
4. i=i+1;
5. else:print("The while loop exhausted");
Output:
1
2
3
4
5
The while loop exhausted
Example 2
1. i=1;
2. while i<=5:
3. print(i)
4. i=i+1;
5. if(i==3):
6. break;
7. else:print("The while loop exhausted");
Output:
1
2
The break is commonly used in the cases where we need to break the loop for a given
condition.
1. #loop statements
2. break;
Example 2
1. str = "python"
2. for i in str:
3. if i == 'o':
4. break
5. print(i);
Output:
p
y
t
h
Output:
Output:
Example 3
1. n=2
2. while 1:
3. i=1;
4. while i<=10:
5. print("%d X %d = %d\n"%(n,i,n*i));
6. i = i+1;
7. choice = int(input("Do you want to continue printing the table, press 0 for
no?"))
8. if choice == 0:
9. break;
10. n=n+1
Output:
Pass Statement
The pass statement is a null operation since nothing happens when it is executed. It is used
in the cases where a statement is syntactically needed but we don?t want to use any
executable statement at its place.
For example, it can be used while overriding a parent class method in the subclass but don't
want to give its specific implementation in the subclass.
Pass is also used where the code will be written somewhere but not yet written in the
program file.
Output:
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.
1. pass
1. for i in [1,2,3,4,5]:
2. if i==3:
3. pass
4. print "Pass when value is",i
5. print i,
Output:
1. >>>
2. 1 2 Pass when value is 3
3. 3 4 5
4. >>>
Python String
Till now, we have discussed numbers as the standard data types in python. In this section of the
tutorial, we will discuss the most popular data type in python i.e., string.
In python, strings can be created by enclosing the character or the sequence of characters in the
quotes. Python allows us to use single quotes, double quotes, or triple quotes to create the string.
Here, if we check the type of the variable str using a python script
In python, strings are treated as the sequence of strings which means that python doesn't support
the character data type instead a single character written as 'p' is treated as the string of length 1.
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.
Example 1
1. str = "HELLO"
2. str[0] = "h"
3. print(str)
Output:
However, in example 1, the string str can be completely assigned to a new content as specified in
the following example.
Example 2
1. str = "HELLO"
2. print(str)
3. str = "hello"
4. print(str)
Output:
HELLO
hello
String Operators
Operator Description
+ It is known as concatenation operator used to join the strings given either side of the opera
* It is known as repetition operator. It concatenates the multiple copies of the same string.
[:] It is known as range slice operator. It is used to access the characters from the specified ra
not in It is also a membership operator and does the exact reverse of in. It returns true if a partic
the specified string.
r/R It is used to specify the raw string. Raw strings are used in the cases where we need to prin
characters such as "C://python". To define any string as a raw string, the character r or R is
% It is used to perform string formatting. It makes use of the format specifiers used in C prog
their values in python. We will discuss how formatting is done in python.
Example
Consider the following example to understand the real use of Python operators.
1. str = "Hello"
2. str1 = " world"
3. print(str*3) # prints HelloHelloHello
4. print(str+str1)# prints Hello world
5. print(str[4]) # prints o
6. print(str[2:4]); # prints ll
7. print('w' in str) # prints false as w is not present in str
8. print('wo' not in str1) # prints false as wo is present in str1.
9. print(r'C://python37') # prints C://python37 as it is written
10.print("The string str : %s"%(str)) # prints The string str : Hello
Output:
HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello
1. Integer = 10;
2. Float = 1.290
3. String = "Ayush"
4. print("Hi I am Integer ... My value is %d\nHi I am float ... My value is %f\nHi I am
string ... My value is %s"%(Integer,Float,String));
Output:
Method Description
decode(encoding = 'UTF8', errors = Decodes the string using codec registered for
'strict') encoding.
rsplit(sep=None, maxsplit = -1) It is same as split() but it processes the string from
the backward direction. It returns the list of words in
the string. If Separator is not specified then the
string splits according to the white-space.
rpartition()
Python Functions
Functions are the most important aspect of an application. A function can be defined as the
organized block of reusable code which can be called whenever required.
Python allows us to divide a large program into the basic building blocks known as function.
The function contains the set of programming statements enclosed by {}. A function can be
called multiple times to provide reusability and modularity to the python program.
In other words, we can say that the collection of functions creates a program. The function
is also known as procedure or subroutine in other programming languages.
Python provide us various inbuilt functions like range() or print(). Although, the user can
create its functions which can be called user-defined functions.
o By using functions, we can avoid rewriting same logic/code again and again in a
program.
o We can call python functions any number of times in a program and from any place
in a program.
o We can track a large python program easily when it is divided into multiple functions.
o Reusability is the main achievement of python functions.
o However, Function calling is always overhead in a python program.
Creating a function
In python, we can use def keyword to define the function. The syntax to define a function in
python is given below.
1. def my_function():
2. function-suite
3. return <expression>
The function block is started with the colon (:) and all the same level block statements
remain at the same indentation.
A function can accept any number of parameters that must be the same in the definition
and function calling.
Function calling
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.
1. def hello_world():
2. print("hello world")
3.
4. hello_world()
Output:
hello world
Parameters in function
The information into the functions can be passed as the parameters. The parameters are
specified in the parentheses. We can give any number of parameters, but we have to
separate them with a comma.
Consider the following example which contains a function that accepts a string as the
parameter and prints it.
Example 1
1. #defining the function
2. def func (name):
3. print("Hi ",name);
4.
5. #calling the function
6. func("Ayush")
Example 2
1. #python function to calculate the sum of two variables
2. #defining the function
3. def sum (a,b):
4. return a+b;
5.
6. #taking values from the user
7. a = int(input("Enter a: "))
8. b = int(input("Enter b: "))
9.
10. #printing the sum of a and b
11. print("Sum = ",sum(a,b))
Output:
Enter a: 10
Enter b: 20
Sum = 30
However, there is an exception in the case of mutable objects since the changes made to
the mutable objects like string do not revert to the original string rather, a new string object
is made, and therefore the two different objects are printed.
Output:
Output:
Types of arguments
There may be several types of arguments which can be passed at the time of function
calling.
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
Required Arguments
Till now, we have learned about function calling in python. However, we can provide the
arguments at the time of function calling. As far as the required arguments are concerned,
these are the arguments which are required to be passed at the time of function calling with
the exact match of their positions in the function call and function definition. If either of the
arguments is not provided in the function call, or the position of the arguments is changed,
then the python interpreter will show the error.
Example 1
1. #the argument name is the required argument to the function func
2. def func(name):
3. message = "Hi "+name;
4. return message;
5. name = input("Enter the name?")
6. print(func(name))
Output:
Output:
Example 3
1. #the function calculate returns the sum of two arguments a and b
2. def calculate(a,b):
3. return a+b
4. calculate(10) # this causes an error as we are missing a required arguments b.
Output:
Keyword arguments
Python allows us to call the function with the keyword arguments. This kind of function call
will enable us to pass the arguments in the random order.
The name of the arguments is treated as the keywords and matched in the function calling
and definition. If the same match is found, the values of the arguments are copied in the
function definition.
Example 1
1. #function func is called with the name and message as the keyword arguments
2. def func(name,message):
3. print("printing the message with",name,"and ",message)
4. func(name = "John",message="hello") #name and message is copied with the values John
and hello respectively
Output:
Output:
If we provide the different name of arguments at the time of function call, an error will be
thrown.
Example 3
1. #The function simple_interest(p, t, r) is called with the keyword arguments.
2. def simple_interest(p,t,r):
3. return (p*t*r)/100
4.
5. print("Simple Interest: ",simple_interest(time=10,rate=10,principle=1900)) # doesn?t find
the exact match of the name of the arguments (keywords)
Output:
The python allows us to provide the mix of the required arguments and keyword arguments
at the time of function call. However, the required argument must not be given after the
keyword argument, i.e., once the keyword argument is encountered in the function call, the
following arguments must also be the keyword arguments.
Example 4
1. def func(name1,message,name2):
2. print("printing the message with",name1,",",message,",and",name2)
3. func("John",message="hello",name2="David") #the first argument is not the keyword argu
ment
Output:
The following example will cause an error due to an in-proper mix of keyword and required
arguments being passed in the function call.
Example 5
1. def func(name1,message,name2):
2. print("printing the message with",name1,",",message,",and",name2)
3. func("John",message="hello","David")
Output:
Default Arguments
Python allows us to initialize the arguments at the function definition. If the value of any of
the argument is not provided at the time of function call, then that argument can be
initialized with the value given in the definition even if the argument is not specified at the
function call.
Example 1
1. def printme(name,age=22):
2. print("My name is",name,"and age is",age)
3. printme(name = "john") #the variable age is not passed into the function however the defa
ult value of age is considered in the function
Output:
Example 2
1. def printme(name,age=22):
2. print("My name is",name,"and age is",age)
3. printme(name = "john") #the variable age is not passed into the function however the defa
ult value of age is considered in the function
4. printme(age = 10,name="David") #the value of age is overwritten here, 10 will be printed
as age
Output:
However, at the function definition, we have to define the variable with * (star) as
*<variable - name >.
Example
1. def printme(*names):
2. print("type of passed argument is ",type(names))
3. print("printing the passed arguments...")
4. for name in names:
5. print(name)
6. printme("john","David","smith","nick")
Output:
Scope of variables
The scopes of the variables depend upon the location where the variable is being declared.
The variable declared in one part of the program may not be accessible to the other parts.
In python, the variables are defined with the two types of scopes.
1. Global variables
2. Local variables
The variable defined outside any function is known to have a global scope whereas the
variable defined inside a function is known to have a local scope.
Example 1
1. def print_message():
2. message = "hello !! I am going to print a message." # the variable message is local to th
e function itself
3. print(message)
4. print_message()
5. print(message) # this will cause an error since a local variable cannot be accessible here.
Output:
Example 2
1. def calculate(*args):
2. sum=0
3. for arg in args:
4. sum = sum +arg
5. print("The sum is",sum)
6. sum=0
7. calculate(10,20,30) #60 will be printed as the sum
8. print("Value of sum outside the function:",sum) # 0 will be printed
Output:
The sum is 60
Value of sum outside the function: 0
>>>
>>> for i in range(5):
... print(i)
...
0
1
2
3
4
The given end point is never part of the generated sequence; range(10) generates 10
values, the legal indices for items of a sequence of length 10. It is possible to let
the range start at another number, or to specify a different increment (even negative;
sometimes this is called the ‘step’):
range(5, 10)
5, 6, 7, 8, 9
range(0, 10, 3)
0, 3, 6, 9
To iterate over the indices of a sequence, you can combine range() and len() as
follows:
>>>