Introduction to Python
• Python is a general-purpose high-level programming language. It is an
open source language
• Guido Van Rossum conceived Python in the late 1980s. He named this
language after a popular comedy show called 'Monty Python's Flying
Circus’
• Python born, name picked -Dec 1989
• Python software Foundation - 2001
What is Python
Multi-paradigm programming language
interpreted language
supports dynamic data types
Independent from platforms
focused on development
simple and easy grammar
high-level internal objects data types
Automatic memory management
It's free (open source)
Features of Python
Embeddable
Huge
Simplicity Open Source Portability and Interpreted
Libraries
Extensible
Machine Learning
GUI
Software Development
Web Development
also called as general purpose Language
Who uses Python
Google
Dropbox
BitTorrent
Nasa
Netflix
YouTube
Raspberry PI
Why learn Python ?
• Fun-to-use "Scripting language"
• Object-oriented, imperative, functional programming and procedure
styles
• highly educational
• very easy to learn, it runs on any platform.
• Powerful, scalable, easy to maintain
• high productivity
• lots of libraries
• interactive front-end for FORTRAN/C/C++ code
Why learn python ?
• reduce development time
• reduce code length
• easy to learn and use as developers
• easy to understand codes
• easy to do team projects
• easy to extend to other languages
Where to use Python ?
• Web development (Django and Flask)
• Data Science - including machine learning, data analysis, and data
visualization
• scripting Graphics user Interface(GUI) embedded
• applications, gaming, DevOps Tools
• Education
Installing Python on Windows
• Python
• IDE -> Integrated development Environment
• PyCharm
• Jupiter Notebook
•
Keywords and Identifiers
• Python Keywords are reserved words in Python.
• They are case-sensitive.
• Currently there are 33 keywords in Python 3.7.
• All these keywords are written in lowercase except True, False and
None.
Python Identifiers
• An identifier in Python is a name given to entities like class, variables,
functions, etc. Identifiers help to differentiate one entity from
another.
Rules for writing identifiers
• 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 _.
• Example: my_variable, var_1, var1 etc.
• An identifier cannot start with a digit.
• Example: 1my_variable, (but you can write my_variable1), 1var (but you can
write var1)
• Keywords cannot be used as identifiers.
• Example: def= 38 + 2
Python Comments
• One of the most important practice in Python is providing comments
in while you write your code.
• You don't want people to have hard time figuring out what is going on
in your code. In fact wring a comment actually helps you to figure
things out easily later on when you revisit your code.
• You can use the hash (#) symbol to write a comment as seen below:
#We are adding two numbers below:
23 + 8
Multi-line Comments
• We can also provide comments on multiple
• We can alternatively use triple quotes to achieve the same thing.
Either (''') or (""")
'''this is an example of
comments using quotes'‘’
"""this is an example of
comments using quotes"""
Variables
• A variable is a named location used to store data in the memory. It is
helpful to think of variables as a container that holds data that can be
changed later in the program.
number = 10
name =“Rajesh”
College = “My College”
Assigning multiple values to multiple
variables
a, b, c = 78, 'TDS', 89.2
print (a)
print (b)
print (c)
Rules and Naming Convention
for Python Variables
Python variable names should have a combination of letters in lowercase (a to z) or
uppercase (A to Z) or digits (0 to 9) or an underscore (_).
• Snake_case = 'I am snake case variable’
• MACRO_CASE = 'I am MICRO CASE variable'
• camelCase = 'I am Camel Case variable'
Make sure your variable name makes sense.
#instead of writing a = ['Red','Green','Blue'],
#write the following instead
colors = ['Red','Green','Blue']
#instead of writing b = ['Female','Male']
#write the following instead
gender = ['Female','Male']
Python Variable Name Rules
• Must start with a letter or underscore _
• Case Sensitive
Good: name age tom25 _max
Bad : 45name #name age.22
Different: name Name NAME
• Identifier name must not contain any white-space, or special character
(!, @, #, %, ^, &, *).
• Reserved Words
You can not use reserved words names/ identifiers
and del for is raise
Data types in Python
• Every value in Python has a datatype.
• Python is completely object oriented, and not "statically typed". You
do not need to declare variables before using them, or declare their
type.
• Every variable in Python is an object.
Numbers
Numbers
Numeric Data types are used to store numerical values in the variables
• Python supports two types of numbers - integers(whole numbers)
and floating point numbers(decimals).
• (It also supports complex numbers).
myint = 7
print(myint)
myfloat = 7.0
print(myfloat)
myfloat = float(7)
print(myfloat)
Strings
• Collection of characters inside single quotes or double quotes
Firstname = “Arun”
Lastname = “Sharma”
What are operators in python?
• Operators are special symbols in Python that carry out arithmetic or
logical computation. The value that the operator operates on is called
the operand.
Arithmetic operators
• Arithmetic operators are used to perform mathematical
operations like addition, subtraction, multiplication, etc.
Operato
Meaning Example
r
+ Add two operands or unary plus x + y+ 2
Subtract right operand from the left or
- x - y- 2
unary minus
* Multiply two operands x*y
Divide left operand by the right one
/ x/y
(always results into float)
Modulus - remainder of the division of left
% x % y (remainder of x/y)
operand by the right
x = 15
y=4
print('x + y =',x+y)
print('x - y =',x-y)
print('x * y =',x*y)
print('x / y =',x/y)
print('x // y =',x//y)
print('x ** y =',x**y)
Comparison operators
• Comparison operators are used to compare values. It returns either
True or False according to the condition.
Comparison operators
Operator Meaning Example
Greater than - True if left operand
> x>y
is greater than the right
Less than - True if left operand is
< x<y
less than the right
Equal to - True if both operands
== x == y
are equal
Not equal to - True if operands are
!= x != y
not equal
Greater than or equal to - True if
>= left operand is greater than or x >= y
equal to the right
Less than or equal to - True if left
<= operand is less than or equal to the x <= y
right
x = 10
y = 12
print('x > y is',x>y)
print('x < y is',x<y)
print('x == y is',x==y)
print('x != y is',x!=y)
print('x >= y is',x>=y)
print('x <= y is',x<=y)
Logical operators
• Logical operators are the and, or, not operators.
Operator Meaning Example
True if both the operands are
and x and y
true
True if either of the operands is
or x or y
true
True if operand is false
not not x
(complements the operand)
Logical operators
x = True
y = False
print('x and y is',x and y)
print('x or y is',x or y)
print('not x is',not x)
Assignment operators
• Assignment operators are used in Python to assign values to variables.
• a = 5 is a simple assignment operator that assigns the value 5 on the
right to the variable a on the left.
• There are various compound operators in Python like a += 5 that adds
to the variable and later assigns the same. It is equivalent to a = a + 5.
Assignment operators
Operator Example Equivalent to
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
• Numeric
• Lists
• Tuples
• Dictionary
• Sets
• String
If Statement
If statements are control flow statements which helps us to run a
particular code only when a certain condition is satisfied. For example,
you want to print a message on the screen only when a condition is
true then you can use if statement
if condition:
block_of_code
num = 3
if num > 0:
print(num, "is a positive number.")
What is if...else statement in Python?
• 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.
Python 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.
if condition:
block_of_code_1
else:
block_of_code_2
if...else
num = 22
if num % 2 == 0:
print("Even Number")
else:
print("Odd Number")
If elif else statement
• The if..elif..else statement is used when we need to check multiple
conditions.
if condition:
block_of_code_1
elif condition_2:
block_of_code_2
elif condition_3:
block_of_code_3
..
..
..
else:
block_of_code_n
Nested If else statement
• When there is an if statement (or if..else or if..elif..else) is present
inside another if statement (or if..else or if..elif..else) then this is
calling the nesting of control statements.
num = -99
if num > 0:
print("Positive Number")
else:
print("Negative Number")
if -99<=num:
print("Two digit Negative Number")
Looping in Python
• A loop statement allows us to execute a statement or group of
statements multiple times.
• 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.
What is while loop in Python?
• The while loop in Python is used to iterate over a block of code as
long as the test expression (condition) is true.
while test_expression:
Body of while
n = 10
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1
print("The sum is", sum)
What is for loop in Python?
• The for loop in Python is used to iterate over a sequence (list, tuple,
string) or other iterable objects. Iterating over a sequence is called
traversal.
for val in sequence:
Body of for
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
sum = 0
for val in numbers:
sum = sum+val
print("The sum is", sum)
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
Python break and continue Statement
• break and continue statements can alter the flow of a normal loop.
• Loops iterate over a block of code until the test expression is false, but
sometimes we wish to terminate the current iteration or even the
whole loop without checking test expression.
Python break statement
• The break statement terminates the loop containing it. Control of the
program flows to the statement immediately after the body of the
loop.
• If the break statement is inside a nested loop (loop inside another
loop), the break statement will terminate the innermost loop.
# Use of break statement inside the loop
for val in "string":
if val == "i":
break
print(val)
print("The end")
Python continue statement
• The continue statement is used to skip the rest of the code inside a
loop for the current iteration only. Loop does not terminate but
continues on with the next iteration.
for val in "string":
if val == "i":
continue
print(val)
print("The end")
What is pass statement in Python?
• In Python programming, the pass statement is a null statement. The
difference between a comment and a pass statement in Python is that
while the interpreter ignores a comment entirely, pass is not ignored.
• pass
• Suppose we have a loop or a function that is not implemented yet,
but we want to implement it in the future. They cannot have an
empty body. The interpreter would give an error. So, we use the pass
statement to construct a body that does nothing.
What is String in Python?
• A string is a sequence of characters.
• String is an immutable sequence data type
• Wrapped inside single, double or triple quotes.
• Triple quotes can be used to represented multiline strings.
How to access characters in a string?
str = 'programiz'
print('str = ', str)
print('str[0] = ', str[0])
print('str[-1] = ', str[-1])
• #slicing 2nd to 5th character
print('str[1:5] = ', str[1:5])
• #slicing 6th to 2nd last character
print('str[5:-2] = ', str[5:-2])
Python String Operations
• There are many operations that can be performed with strings which
makes it one of the most used data types in Python.
Concatenation of Two or More Strings
• Joining of two or more strings into a single one is called
concatenation.
• The + operator does this in Python. Simply writing two string literals
together also concatenates them.
• The * operator can be used to repeat the string for a given number of
times.
• # Python String Operations
• str1 = 'Hello'
• str2 ='World!’
• print('str1 + str2 = ', str1 + str2)
• print('str1 * 3 =', str1 * 3)
Iterating Through a string
• We can iterate through a string using a for loop. Here is an example to
count the number of 'l's in a string.
count = 0
for letter in 'Hello World':
if(letter == 'l'):
count += 1
print(count,'letters found')
Python String Functions
• capitalize() : Converts the first character to upper case
• index() :
• replace () :
• replace () :This method is used to replace the string, which accepts
two arguments.
• reversed() :This method is used to reverse a given string
• join() :This method returns the string concatenated with the elements
of iterable.
• split() :This method is used to split the string based on the user arguments
• len () : This method returns the length of the String.
• lower () : This method is used to convert the uppercase to lowercase.
• upper () : This method is used to convert the lowercase to uppercase
• isupper()
• 1.True- If all characters in the string are uppercase.
• 2.False- If the string contains 1 or more non-uppercase characters.
• islower())
• String Compare : This method is used to compare two strings.
Python Type Casting
• In Python, Type Casting is a process in which we convert a literal of one type to
another.
• Inbuilt functions int(), float() and str() shall be used for typecasting.
int() can take a float or string literal as argument and returns a value of class 'int'
type.
float() can take an int or string literal as argument and returns a value of class
'float' type.
str() can take a float or int literal as argument and returns a value of class 'str' type.
Lists in Python
• A list of a collection of objects. Somewhat kind of an array in many other
programming language but more flexible.
• This data can be an integer, a float, a complex number, a String or any datatype in
python.
• Python lists are a type of sequence. Each object in a list is assigned an index as is
typical for all sequence. These objects can be manipulated using its respective
index.
• Python has both forward and backwards index number, so for each element there
exists one positive and one negative number to access that element.
• While defining a list, we have to enclose each element of the list within square
brackets, and each element is separated by commas.
Features of Python lists:
• Lists are ordered.
• Lists elements can be manipulated using its index.
• Lists are mutable
• Lists are Dynamic
• Lists can contain objects
• Lists can be nested to depth
• myEmptyList = []
• mylist = [9, 4, 3, 2, 8]
Deriving from another List
• myList1 = ['first', 'second', 'third', 'fourth', 'fifth’]
• myList2 = myList1
Using Loops with List
Deleting an element from a List
• pop( ) function: This method requires the index number of the
element that you want to delete. For example, if you want to delete
the 5th element of the list, then just do it like:
myList.pop(4)
del keyword:
• This also requires the index number.
• del myList[4]
remove( ) function:
• This function, instead of index number, requires the value that has to
be deleted.
Convert a List to String
• If you want to convert your list into a string to print it as output, you
can do it easily without using any loop.
Tuples
• A Tuples contains a group of elements which can be same or different types
• Tuples are immutable (unchangeable).
• Once tuple is created you can’t update data inside tuple.
• It is similar to List but Tuples are read-only which means we ca not modify it’s
element.
• Tuples are used to store data which should not be modified.
• It occupies less memory compare to List.
• Tuples are represented using Parenthesis ()
• Tuple items are ordered, and allow duplicate values.
• We can create tuple by writing elements separated by commas inside Parenthesis.
Methods
• Count()
• Index()
• Len()
• slicing
Dictionaries in Python
• Dictionaries are much like lists with an extra parameter called keys.
Recall, how in lists and strings, we used the index as the parameter to
access each element of the string/list. The main differentiating factor
between a list and a dictionary would be, that instead of the index we
use keys to access the elements of a dictionary (or values to access
keys, works both ways).
Creating a Dictionary
• Since we have flexibility in providing the key for each element in the
dictionary, we will have to define each key explicitly.
Key Value
Key-1 Element-1
Key-2 Element-2
Key-3 Element-3
Key-4 Element-4
Key-5 Element-5
• myDictionary = {‘Maths’: 58, ‘Science’: 68, ‘English': ‘65', ‘IT': ‘91'}
Functions in Python
• Python includes many built-in functions.
• These functions perform a predefined task and can be called upon in
any program, as per requirement.
• However, if you don't find a suitable built-in function to serve your
purpose, you can define one.
Functions in Python
• A function is a reusable block of programming statements designed to
perform a certain task.
• Divide the whole program into sub-parts thereby making it more
readable, easy to revise the code and to fix any errors
• We can create our own functions in python, which are also called as
user-defined functions.
• To define a function, Python provides the def keyword.
Advantage of Functions in Python
• Using functions, we can avoid rewriting the same logic/code again
and again in a program.
• We can call Python functions multiple times in a program and
anywhere in a program.
• We can track a large Python program easily when it is divided into
multiple functions.
• Reusability is the main achievement of Python functions.
Structure of function definition
def function_name(parameters):
statement1
statement2
...
...
return [expr]
Defining a Function
∙ Function block should always begin with the keyword ‘def, followed by the
function name and parentheses.
∙ We can pass any number of parameters or arguments inside the
parentheses.
∙ The block of a code of every function should begin with a colon (:)
∙ The first statement in the function body can be a string, which is called the
docstring. It explains the functionality of the function/class. The docstring is not
mandatory.
∙ An optional ‘return’ statement to return a value from the function.
def greet():
"""This function displays 'Hello World!'"""
print('Hello World!')
Calling a Function
• To call a defined function, just use its name as a statement anywhere
in the code.
• In Python, after the function is created, we can call it from another
function. A function must be defined before the function call;
otherwise, the Python interpreter gives an error. To call the function,
use the function name followed by the parentheses.
def greet():
"""This function displays 'Hello World!'"""
print('Hello World!’)
greet()
Function Parameters
•It is possible to define a function to receive one or more parameters (also
called arguments) and use them for processing inside the function block.
•Parameters/arguments may be given suitable formal names.
•The greet() function is now defined to receive a string parameter called
name. Inside the function, the print() statement is modified to display the
greeting message addressed to the received parameter.
•We can define any number of parameters while defining a function.
def greet(name):
print ('Hello ', name)
greet(‘Raj') # calling function with argument
greet(123)
• The function parameters can have an annotation to specify the type
of the parameter using parameter:type syntax. For example, the
following annotates the parameter type string
def greet(name:str):
print ('Hello ', name)
greet('Steve') # calling function with string argument
greet(123) # raise an error for int argument
Multiple Parameters
• A function can have multiple parameters. The following function takes
three arguments.
def greet(name1, name2, name3):
print ('Hello ', name1, ' , ', name2 , ', and ', name3)
greet(‘Rajesh', ‘Suresh', ‘Ramesh') # calling function with string argument
Function with Return Value
• Most of the time, we need the result of the function to be used in further
processes. Hence, when a function returns, it should also return a value.
• A user-defined function can also be made to return a value as a result of
the function . . It terminates the function execution and transfers the result
where the function is called. The return statement cannot be used outside
of the function. In this case, the returned value has to be assigned to some
variable.
def additions(a, b):
sum = a+b
return sum
print(“Sum is: “, additions(2, 3))
4 types of arguments
Required argument
Keyworded argument
Default argument
Variable length arguments
Required Arguments:
• Required arguments are the arguments which are passed to a
function in a sequential order, the number of arguments defined in a
function should match with the function definition.
Keyworded Arguments:
• When we use keyword arguments in a function call, the caller
identifies the arguments by the argument name.
def greet(firstname, lastname):
print ('Hello', firstname, lastname)
greet(lastname='Jobs', firstname='Steve’)
Default Arguments:
• While defining a function, its parameters may be assigned default
values. This default value gets substituted if an appropriate actual
argument is passed when the function is called. However, if the actual
argument is not provided, the default value will be used inside the
function.
def greet(name = 'Guest'):
print ('Hello', name)
greet()
greet(‘Raj')
Variable-length Arguments:
• A function in Python can have an unknown number of arguments by
putting * before the parameter if you don't know the number of
arguments the user is going to pass.
def greet(*names):
print ('Hello ', names[0], ', ', names[1], ', ', names[2])
greet(‘Rajesh', ‘Suresh', ‘Ramesh’)
def printme(*names):
print("type of passed argument is ",type(names))
print("printing the passed arguments...")
for name in names:
print(name)
printme(‘Rajesh', ‘Suresh', ‘Ramesh’)
def greet(*names):
i=0
print('Hello ', end=''”)
while len(names) > i:
print(names[i], end=', ')
i+=1
greet(‘Rajesh', ‘Suresh', ‘Ramesh’)
greet(‘Rajesh', ‘Suresh', ‘Ramesh’, "Naresh")
Scope and Lifetime of variables
• Scope of a variable is the portion of a program where the variable is
recognized. Parameters and variables defined inside a function are not
visible from outside the function. Hence, they have a local scope.
• The lifetime of a variable is the period throughout which the variable
exits in the memory. The lifetime of variables inside a function is as long
as the function executes.
• They are destroyed once we return from the function. Hence, a function
does not remember the value of a variable from its previous calls.
local variable
• variable that is defined in a block and available in that block only.
• It is not accessible outside the block. Such variable is called as local
variable
def goodEvening():
name="Raj" #local variable
print("good evening ", name)
goodEvening()
Global variable
• Any variable present outside of any function is called a global variable.
• Its value is accessible from inside any function.
name="Raj" #global variable
def goodEvening():
print("Good evening ", name)
def goodMorning():
print("Good morning ", name)
goodEvening()
print(name)
goodMorning()
The global Keyword
• Normally, when you create a variable inside a function, that variable is
local, and can only be used inside that function.
• To create a global variable inside a function, you can use the global
keyword.
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
def greet(name, msg):
"""This function greets to
the person with the provided message"""
print("Hello", name + ', ' + msg)
greet("Monica", "Good morning!")